运行 外部程序,当脚本来自 cron 运行

Run external program when script is run from cron

我有一个 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 运行s。 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 的绝对路径来解决它,但感觉这是个坏主意。但我可能错了。如果这是正确的方法,请解释原因。

您可能需要在 crontab 中定义 shell。 之前已经问过这个问题。

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

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

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

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