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

Categories: python Tags: ,
  1. Ben
    April 17, 2012 at 09:13

    First logical post I have senn, Thank you

  2. July 16, 2014 at 20:43

    In my case it was not necessary the PYTHONPATH but the SHELL and PATH environmental variables

  3. August 6, 2014 at 13:56

    I was looking for cron to work on raspberry pi. This post helped. Thanks.

  4. September 5, 2016 at 17:35

    the log file gives me: “no display name and no $DISPLAY environment variable”

    • September 5, 2016 at 18:16

      Add this line too:


  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: