Home > python > Calling a Python script from crontab

Calling a Python script from crontab

You want to call a Python script of yours from crontab but it doesn’t really want to work :(

First, redirect everything to a file, thus you can check the error messages. For testing, let’s call the script at every minute. Edit your crontab settings with “crontab -e“.

* * * * * python /absolute/path/to/script.py >>/tmp/out.txt 2>&1

Don’t redirect to /var/log/cronrun (as many guides suggest), because if you have no rights to modify it, you won’t see anything… Choose a file where you can write to.

Then start checking the output of the log file:

touch /tmp/out.txt
tail -f /tmp/out.txt

tail -f” monitors the file constantly and prints every change.

Bare in mind that crontab doesn’t read your startup settings from .bashrc for instance, thus if you added something to PYTHONPATH, it won’t be visible! You have to repeat your PYTHONPATH settings in crontab too. “Each directory you need will have to be listed, because you can’t append to it since the previous value isn’t available.” (tip from here)

* * * * * python /absolute/path/to/script.py >>/tmp/out.txt 2>&1

If it works, customize the execution time of the script by changing the “* * * * *” part.

You may also have problems with imports. Say your script wants to import another module from a different folder. In this case you can have a look at this post: Import a file from another directory of the project.

Related posts

About these ads
Categories: python Tags: ,
  1. Ben
    April 17, 2012 at 09:13 | #1

    First logical post I have senn, Thank you

  1. No trackbacks yet.
You must be logged in to post a comment.

Get every new post delivered to your Inbox.

Join 63 other followers

%d bloggers like this: