Home > Linux, Python > crontab shell

crontab shell

I wrote a Python script that I want to run every five minutes through a crontab. The script ran fine and linked with my local libraries until I ran it through the crontab and it couldn’t find my local libraries. After a bit of thought, I realized that the crontab was not running through the same shell environment as I expected it to. Apparently the shell is set in /etc/crontab file and there it was set to bash. That in turn was calling the wrong version of Python, and that was why my local Python scripts weren’t being found.

There are four different ways around this:
1) Modify /etc/crontab to hit the right shell; in my case (first line modified):
/etc/crontab

SHELL=/bin/tcsh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

crontab -e

*/5 * * * * python /my/script.py

2) Add the shell value to the top of the custom crontab (crontab -e); in my case:

SHELL=/bin/tcsh

*/5 * * * * python /my/script.py

3) Run the actual command through the tcsh as so:

*/5 * * * * tcsh -c "python /my/script.py"

4) Directly request the right version of Python:

*/5 * * * * /tools/bin/python /my/script.py
Categories: Linux, Python Tags:
  1. Jayawant
    December 18th, 2013 at 22:15 | #1

    As you mentioned shell can be changed by the following four ways. If the script I call in crontab in turn call a script running in some other shell in that case what should be done to change the shell.

  1. No trackbacks yet.