1

I have a Python script that works when run from the normal Terminal (and from any location) but fails when running from cron, throwing a KeyError: 'PATH' error.

A comment on this post suggests that this is because cron runs with a different environment. When I switch using env -i /bin/bash --noprofile --norc as suggested, the KeyError is raised and appears to be from os.environ["PATH"] not being set, which I can confirm.

How do I set that, and to what? Can I make this permanent for cron?

EDIT: My question is very similar to some others, but different in that it threw a specific error from Python – I think keeping this question will help if anyone gets the same KeyError?

4
  • 1
    what causes the error exactly? Do you try to open a file that is supposed to be contained in the same folder as your script? If yes, you can get the path of your current script via os.path.dirname(os.path.realpath(__file__)) if that's of any help. Commented Sep 19, 2017 at 15:15
  • 1
    Possible duplicate of How to get CRON to call in the correct PATHs Commented Sep 19, 2017 at 15:17
  • It's an installed library calling os.environ["PATH]. My libraries are all in my user's bin folder. Commented Sep 19, 2017 at 15:17
  • @LaurentLAPORTE – very similar, yeah didn't see that one in my searching. Doesn't come from the KeyError though, so maybe this specific situation is helpful to others? Commented Sep 19, 2017 at 15:20

1 Answer 1

2

You need to define your environment variables, like PATH in your /etc/crontab file.

Eg.:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user   command
01 01 * * 1-5 root python /path/to/file.py

See: https://stackoverflow.com/a/2409369/1513933

Sign up to request clarification or add additional context in comments.

3 Comments

Super helpful – is there a way to test this outside of a cron job? (ie directly from the Terminal instead of changing the times over and over?)
Yes, you can try su - login, where login is the login of the cron. And then execute the Python code.
Hmm, how do I know the login of the cron? (Your solution worked, by the way!)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.