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/

user2314737
  • 27,088
  • 20
  • 102
  • 114
Quetzalcoatl
  • 2,016
  • 4
  • 26
  • 36

1 Answers1

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.

user2314737
  • 27,088
  • 20
  • 102
  • 114
  • 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. – Quetzalcoatl Sep 03 '14 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? – Quetzalcoatl Sep 03 '14 at 14:40
  • Hi. Concerning your follow-up questions. The reason why `cron` doesn't read users' environment variables is security. Standard reference for `cron`is the Unix manual page e.g. http://www.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. – user2314737 Sep 04 '14 at 06:22