Executing python3 file with a cron job.

帅比萌擦擦* 提交于 2019-12-03 14:10:30

The reason why you don't get the file forecast.txt in directory /home/valence when using crontab job * * * * * /home/valence/Get_forecast.py is that the cron don't execute the command in directory /home/valence and you specified the file forecast.txt in relative path form in your program. So the file is created somewhere else.

To get the expected file output, you can use the following crontab job:

* * * * * cd /home/valence && ./Get_forecast.py

This explicitly assign the current working directory to be /home/valence, and execute the script from there.

What's more, to get the output from stdout and stderr, add redirection is always helpful when something unexpected happens:

* * * * * cd /home/valence && ./Get_forecast.py > /tmp/forecast.log 2>&1

Note:

The previous two crontab job assumes Get_forecast.py jexecutable and with shebang specified. The ./Get_forecast.py part can always be replaced with python3 Get_forecast.py or /usr/bin/python3 Get_forecast.py to be more clear.

What worked for me to run a python3 script is the next:

* * * * * /usr/local/bin/python3 /Users/gabriel/python/myScript.py

Using which python3 find the path to your python version and then add the path to your file.

I use this tool to generate the command and I usually do something like

 10 * * * * /home/valence/Get_forecast.py > /dev/null 2>&1

i think your cronjob is not at all running your program. Way to run a program is like this

python script.py

so your cronjob must look like this.

* * * * * python /home/valence/Get_forecast.py

or

* * * * * cd /home/valence && python Get_forecast.py

you can send all the outputs of a cronjob to a log file like this.

* * * * * cd /home/valence && python Get_forecast.py >> output_logs.op

I'd recommend providing an absolute path to the output file:

forecast=open("/tmp/forecast.txt", "w+")

Cron gets a little funny with paths / permissions and ownership of scripts that execute. Let me know if the file gets created under /tmp.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!