我想使用 Cron 每天每小時執行我的 python 腳本。因此我創建了一個如下所示的 cronjob:@hourly /home/pi/Desktop/repository/auslastung_download/auslastung.pycronjob 應執行以下腳本:from bs4 import BeautifulSoupfrom selenium.webdriver.firefox.options import Options as FirefoxOptionsfrom selenium import webdriverfrom datetime import datetime, datedef get_auslastung_lichtenberg(): try: url = "https://www.mcfit.com/de/fitnessstudios/studiosuche/studiodetails/studio/berlin-lichtenberg/" options = FirefoxOptions() options.add_argument("--headless") driver = webdriver.Firefox(options=options) driver.get(url) html_content = driver.page_source soup = BeautifulSoup(html_content, 'html.parser') elems = soup.find_all('div', {'class': 'sc-iJCRLp eDJvQP'}) #print(elems) auslastung = str(elems).split("<span>")[1] #print(auslastung) auslastung = auslastung[:auslastung.rfind('</span>')] #print(auslastung) auslastung = str(auslastung).split("Auslastung ")[1] #print(auslastung) auslastung = auslastung[:auslastung.rfind('%')] print(auslastung) now = datetime.now() current_time = now.strftime("%H:%M:%S") #print("Current Time =", current_time) today = date.today() print(today) ergebnis = {'date': today, 'time': current_time,'studio': "Berlin Lichtenberg", 'auslastung': auslastung} return ergebnis finally: try: driver.close() except: pass"""import jsonwith open('database.json', 'w') as f: json.dump(get_auslastung_lichtenberg(), f) """import csvwith open('/home/pi/Desktop/repository/auslastung_download/data.csv', mode='a') as file: fieldnames = ['date', 'time', 'studio', 'auslastung'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writerow(get_auslastung_lichtenberg())通過執行時python3 auslastung.py一切正常并且腳本寫入 data.csv 文件。
1 回答

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
首先,您必須確保腳本運行。
如果以交互方式運行,python3 auslastung.py
為什么在 cron 上以不同的方式調用 python 腳本。
您是否嘗試過以交互方式運行/home/pi/Desktop/repository/auslastung_download/auslastung.py
?沒有初始python3
,它會運行嗎?
python3 auslastung.py
如果您的腳本在 crontab 上運行,您應該包含解釋器和腳本的完整路徑:
@hourly /paht/to/python3 /full/path/to/script.py
如果您使腳本直接運行而不需要指示解釋器,那么 /full/path/to/script.py
您應該在 crontab 上包含腳本的完整路徑:
@hourly /full/path/to/script.py
您可以包含一個 shebang:腳本的第一行指示使用哪個解釋器來執行它。所以你的第一行應該是#!/path/to/your/interpreter
然后您必須確保該腳本具有執行權限chmod +x auslastung.py
。
添加回答
舉報
0/150
提交
取消