简体   繁体   English

尽管脚本在手动运行时有效,但 Crontab 没有在 macOS 中运行我的 python 脚本

[英]Crontab isn't running my python script in macOs although the script works when run manually

My school always wants us to download pptx and docx for lecture and practicals and I hate that I'll need to always manually delete it after reading finish.我的学校总是希望我们下载 pptx 和 docx 用于讲座和实践,我讨厌我总是需要在阅读完成后手动删除它。 Therefore I'd created a script that trashes whatever's in the folder and would like crontab to schedule it to run every hour.因此,我创建了一个脚本来丢弃文件夹中的任何内容,并希望 crontab 安排它每小时运行一次。

Everything works fine when I manually run this code through the terminal.当我通过终端手动运行此代码时,一切正常。

def remove_trash():
    import os
    dir_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(dir_path, "trash_script.py")
    with open(filename, "r") as f:
        _ = f.read()
    os.system(f"rm -df {dir_path}/* && touch {filename}")
    with open(filename, "w") as f:
        f.write(_)
        
if __name__ == "__main__":
    remove_trash()

But when I had added this in my crontab,但是当我在我的 crontab 中添加这个时,

0 * * * * python ~/Desktop/Projects/script/Trash/trash_script.py

I tried giving the file permission to execute but it still wouldn't run at every minute 0.我尝试授予文件执行权限,但它仍然不会在每分钟 0 时运行。

chmod +x trash_script.py

I'll suggest to move your script into a bash script first, and add some logs to find the issue.我建议先将您的脚本移动到 bash 脚本中,并添加一些日志以查找问题。 The bash script will look like this: bash 脚本将如下所示:

trash.sh

cd ~/Desktop/Projects/script/Trash
python trash_script.py

Change the execution permissions of your script更改脚本的执行权限

chmod +x trash.sh

Modify your cron job to look like this:将您的 cron 作业修改为如下所示:

0 * * * * sh <path_to_bash_script>/trash.sh >> ~/Desktop/Projects/script/Trash/trash.log 2>&1

This will help to have some output every time the script runs.这将有助于在每次脚本运行时获得一些 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM