0

I am trying to get a cronjob to run a basic Python script as a proof-of-concept exercise. The Python script goes as follows:

#!/usr/bin/python
with open('realfile','a+') as f:
     f.write('testwrite\n')

My script is located (along with the 'realfile' file) in a 'Documents' directory that is one below my home directory (i.e. $HOME/Documents).

My crontab is as follows:

*/1 * * * * /$HOME/Documents/crontest.py

For some reason the crontab does not execute the script every minute as it should. The script works fine, as I manually ran it from command line (using ./crontest.py). In addition, the crontab worked completely fine when the script was located in the home directory and the crontab was simply:

*/1 * * * * /$HOME/crontest.py

I have checked the location of 'crontest.py' using 'locate crontest.py' and I got the following two locations:
/home/meric/crontest.py /usr/bin/crontest.py

I tried setting both of these paths in my crontab, and still the job won't run.

What could be the problem? Thanks for the help!

4

3 回答 3

1

AFAIK,cron作业的工作目录是他们执行的用户的家。因此,如果您同时拥有crontest.pyrealfile在您的Documents子目录中,则应该执行,然后在您家中crontest.py找不到它时失败。realfile像欧文所说的那样重新检查路径;此外,您可以使用它在任意工作目录中运行:

*/1 * * * * cd /home/meric/Documents && ./crontest.py
于 2013-07-16T04:39:40.980 回答
0

您的脚本不在目录中:

/$HOME/Documents/crontest.py

你在底部说它在:

/home/meric/crontest.py /usr/bin/crontest.py

为什么不复制到:

$HOME/Documents/crontest.py

然后再试一次。

于 2013-07-16T04:34:55.833 回答
0

我认为您错过了 python 代码的绝对路径。尝试这个:

#!/usr/bin/python
import os
with open((os.getenv('HOME') + '/Documents/' +'realfile'),'a+') as f:
   f.write('testwrite\n')

并编辑 cron 作业:

*/1 * * * * $HOME/Documents/crontest.py

因为$HOME变量已经包含/

于 2013-07-16T04:45:58.433 回答