Home » Linux » Execute python Script on Crontab

Execute python Script on Crontab

Posted by: admin December 7, 2017 Leave a comment

Questions:

I’m trying to execute a python script using the linux crontab, but I found a lot of solutions and none of them works. For example: edit the anacron at /etc/cron.d or use crontab -e.

I want to run this script every 10 minutes.

What file must I edit to configure this?

Thanks in advance

EDIT

I put this line at the end of the file, but it doesn’t changes anything. Do I have to restart any service?

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py

EDIT [2]

Guys, I have followed the source code. There maybe a problem here, but when I execute it manually, it works:

http://pastebin.com/qsWHNzqT

Answers:

Just use crontab -e and follow the tutorial here:

http://adminschoice.com/crontab-quick-reference

Look at point 3 for a guide on how to specify the frequency.

Based on your requirement, it should effectively be:

*/10 * * * * /usr/bin/python script.py

Questions:
Answers:

Put your script in a file foo.py starting with

#!/usr/bin/python

then give execute permission to that script using

chmod a+x foo.py

and use the full path of your foo.py file in your crontab.

See documentation of execve(2) which is handling the shebang

Questions:
Answers:

As you have mentioned doesn’t changes anything,

First, you should redirect both stdin and stderr from crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

then you can view the file /tmp/listener.log to see if the script executed as you expect.

Second, guess what you mean change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json','r+w')

the crontab job above won’t create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create these file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, then you can view the files created in place.

Leave a Reply

Your email address will not be published. Required fields are marked *