5

I have a Python driver and library scripts that are siblings:

/home/mydir/pythonProjs/
  • driver.py

  • lib.py

In driver.py I have the line:

from lib import method1

The following is successful from my command line on Linux:

python /home/mydir/pythonProjs/driver.py

But when I try the following in crontab:

10 1 * * * export PYTHONPATH=~/mydir/pythonProjs; python /home/mydir/pythonProjs/driver.py

I get the error:

ImportError: No module named lib.method1

I have also attempted changing path setting in my crontab command to the fully-qualified path /home/mydir/pythonProjs, omitting the 'export', and have also attempted writing .sh files (with the necessary #!bin/bash...)

I have one main question and a follow-up question: main: What is a best practice way to fix my problem? follow-up: What is the philosophy behind cron having different path access than my shell?

Before I get down voted too quickly, I will mention that I have read but have not been successful (or correctly parsed) the following: - Where can I set environment variables that crontab will use? - Crontab Issues running Python - http://pythonadventures.wordpress.com/2012/03/31/calling-a-python-script-from-crontab/

1 Answer 1

7

Try to print out environment variables from a dummy job

* * * * * env > /tmp/env.output

as suggested in https://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work

Also check what shell crontab is using. You can set the $SHELL environment variable to bash by adding a line

SHELL=/bin/bash

at the beginning of the crontab file.

3
  • 1
    thank you! In addition to the SHELL command you suggested at the top of my crontab it was also necessary for me to add this shebang at the top my driver.py script: #!/usr/bin/env python Oddly, if I don't include the latter and $ journalctl from home, then I don't see any errors logged from cron but the driver.py does not fully execute (e.g. it seems to not import lib.py). Thanks also for the env > suggestion. Commented Sep 3, 2014 at 14:34
  • 1
    if I may, could you address the follow-up? For example, how might an amateur like myself have come up with the SHELL=/bin/bash and #!/usr/bin/env python solution on my own? What might have been some "standard" references about cron and/or Python that could have led me down the right path? Commented Sep 3, 2014 at 14:40
  • Hi. Concerning your follow-up questions. The reason why cron doesn't read users' environment variables is security. Standard reference for cronis the Unix manual page e.g. unix.com/man-page/linux/5/crontab And finally, asking about "best practices" is off-topic on SO and anyway I don't have a good answer for that. Commented Sep 4, 2014 at 6:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.