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?

JeffThompson
  • 1,538
  • 3
  • 24
  • 47
  • 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. – offeltoffel Sep 19 '17 at 15:15
  • 1
    Possible duplicate of [How to get CRON to call in the correct PATHs](https://stackoverflow.com/questions/2388087/how-to-get-cron-to-call-in-the-correct-paths) – Laurent LAPORTE Sep 19 '17 at 15:17
  • It's an installed library calling `os.environ["PATH]`. My libraries are all in my user's `bin` folder. – JeffThompson Sep 19 '17 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? – JeffThompson Sep 19 '17 at 15:20

1 Answers1

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

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103