簡體   English   中英

在啟動時或使用 crontab 自動運行 python 腳本時出現問題

[英]a problem with running a python script automatically on boot or with crontab

我有一個腳本可以在 PythonAnywhere 上運行我的 Telegram 機器人。 我的 PythonAnywhere 帳戶是免費的,但有限制,它會在 24 小時或更短時間后重新啟動,我不確定確切的時間,我的機器人也會關閉。 因此,我編寫了一個腳本,在 24 小時后從我的 PC 自動運行機器人。 當我正常運行腳本時,它運行良好。 但是當我把它放到啟動列表里讓它自動運行的時候,它卻沒有。 而且我把它放到crontab列表后,還是沒有運行。

這是我的腳本:

#!/usr/bin/env python

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime as dt
from credentials import username, password
import time
import notify2

# Open a web browser and navigate to the website
driver = webdriver.Firefox()
wait = WebDriverWait(driver, 20)
driver.get("https://www.pythonanywhere.com/login/?next=/")

# Locate the login form and enter user & pass, then click on login
wait.until(EC.presence_of_element_located((By.ID, "id_next")))
driver.find_element(By.ID, "id_auth-username").send_keys(username)
driver.find_element(By.ID, "id_auth-password").send_keys(password)
driver.find_element(By.ID, "id_next").submit()

# Locate the bot link and click on it and wait to load the console
wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "NoNameCh")))
driver.find_element(By.PARTIAL_LINK_TEXT, "NoNameCh").click()

# Locate the run button and click on it then quit the browser and wait
driver.find_element(By.CSS_SELECTOR, "button.btn-info.run_button").click()
time.sleep(20)
driver.quit()

# Show notification
notify2.init("Automation")
notification = notify2.Notification("Bot Started!")
notification.set_timeout(10)
notification.show()

# Write a result in the file
path = "~/Dropbox/Projects/python/mypy/automation/result.txt"
with open(path, "a") as f:
    f.write(str(dt.today()) + "\n")

我制作了另一個腳本並將其放入 crontab 列表中。 這是一個腳本,在運行時會返回我知道它啟動的特定文件中的一個詞。 每 24 小時后,第二個腳本將返回結果,但我的主腳本不會執行任何操作。

這是第二個腳本:

#!/usr/bin/env python

path = "~/Dropbox/Projects/python/mypy/automation/result.txt"
with open(path, "a") as f:
    f.write("test file...\n")

這是兩天后的結果文件:

2023-01-08 18:04:07.526809
test file...
test file...

當我手動運行腳本時,第一行已附加。 通常,我應該得到兩個結果(腳本運行的時間和“測試文件...”)。

有什么問題?

我找到了答案。 使用 GUI 元素的腳本在 crontab 中不起作用,因為 crontab 中的腳本在終端中運行。 我還沒有找到一種方法來自動運行我的腳本。 我還在尋找...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM