Home > python > Calling a Python script from crontab

Calling a Python script from crontab

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

Solution
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)

PYTHONPATH=/dir1:/dir2
* * * * * 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.

Troubleshooting
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's avatar
    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:

      DISPLAY=:0

  1. No trackbacks yet.

Leave a comment

Design a site like this with WordPress.com
Get started