【问题标题】:Run external program when script is run from cron从 cron 运行脚本时运行外部程序
【发布时间】:2020-09-05 11:30:22
【问题描述】:

我有一个从命令行执行时可以正常工作的 python 脚本。但是当我尝试从 cron 运行它时,它不起作用。

command = "rsync -avHP --delete --bwlimit=800 rsync://mirror.nsc.liu.se/CentOS/7.8.2003/  /home/me/reposync/centos"
proc=subprocess.run(command.split(), capture_output=True)

cronjob 运行。 cronfile 看起来像这样:

PATH=/home/me
40 13 * * * me cd $PATH && ./reposync.py sync 2> /tmp/test.txt

但我从print(proc.stderr.decode('utf-8')) 收到此错误(是的,两次):

-avHP: rsync: command not found

问题似乎与找不到rsync 有关,但我不知道该怎么办。

/tmp/test.txt 的输出:

FileNotFoundError: [Errno 2] No such file or directory: 'rsync'

我尝试将shell=True 添加到subprocess.run,但似乎没有什么不同。或者它不会抛出那个异常,但是从 proc 打印 stderr 时我仍然得到同样的错误。

我想我可以通过包含rsync 的绝对路径来解决它,但感觉这是个坏主意。但我可能错了。如果这是正确的方法,请解释原因。

【问题讨论】:

    标签: python python-3.x cron subprocess


    【解决方案1】:

    在您的 crontab 中,您将覆盖您的 $PATH 变量,该变量现在仅包含目录 /home/me。现在找不到您的 rsync 可执行文件,因为它不在您的主目录中。

    通过删除 PATH=... 行并使用其完整路径调用脚本来更改您的 crontab 条目:

    40 13 * * * me /home/me/reposync.py sync 2> /tmp/test.txt
    

    【讨论】:

      【解决方案2】:

      您可能必须在 crontab 中定义 shell。 这个问题之前已经问过了。

      crontab: python script being run but does not execute OS Commands

      【讨论】:

        猜你喜欢
        • 2013-09-26
        • 1970-01-01
        • 2014-11-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-15
        • 2018-02-22
        • 2010-09-07
        • 2013-11-26
        相关资源
        最近更新 更多