Cronjob不执行python脚本

时间:2020-10-07 14:06:25

标签: python linux cron raspberry-pi

我想每天使用Cron来执行我的python脚本。因此,我创建了一个cronjob,其外观类似于:@hourly /home/pi/Desktop/repository/auslastung_download/auslastung.py

cronjob应该执行以下脚本:

from bs4 import BeautifulSoup
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver
from datetime import datetime, date


def 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 json

with open('database.json', 'w') as f:
    json.dump(get_auslastung_lichtenberg(), f)
    """

import csv

with 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 个答案:

答案 0 :(得分:0)

首先,您必须确保脚本运行。

如果以交互方式运行python3 auslastung.py,为什么要在cron上以不同的方式调用python脚本。

您是否尝试过仅以交互方式运行/home/pi/Desktop/repository/auslastung_download/auslastung.py?没有最初的python3,它可以运行吗?

如果您的脚本在crontab上以python3 auslastung.py运行,则应同时包含解释器和脚本的完整路径:

@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执行渗透。

相关问题