Python3: configparser KeyError when run as Cronjob

btzs picture btzs · Apr 3, 2015 · Viewed 7.9k times · Source

i have a simple python3 Script that works when I'm running it from console:

import configparser

file = 'config_test.ini'
config = configparser.ConfigParser()
config.read(file)
for key in config['test_section']: print(key)

the called ini-file looks like this:

[test_section]
testkey1 = 5
testkey2 = 42878180
testkey3 = WR50MS10:1100012307
testkey4 = WR50MS04:1100012010
testkex5 = 192.168.200.168

and the script runs fine and returns the five keys of the ini-file.

No I configured it as a cronjob every minute (running on rasbian on Raspberry Pi) via:

* * * * * python3 /home/pi/s0/testconfig.py >> /tmp/cron_debug_log.log 2>&1

and the log looks like this:

Traceback (most recent call last):
  File "/home/pi/s0/testconfig.py", line 7, in <module>
    for key in config['test_section']: print(key)
  File "/usr/lib/python3.2/configparser.py", line 941, in __getitem__
    raise KeyError(key)
KeyError: 'test_section'

Does anyone have an idea what I did wrong Kind regards

Answer

shx2 picture shx2 · Apr 3, 2015

When running from cron, your script runs in a different working directory. This means the filename it is trying to open is relative to a different directory.

You should use the absolute path to the config file in your script.

A common way of doing it in python, assuming the config file resides in the same directory as the script you're running, is using the __file__ builtin:

config_file = os.path.join(os.path.dirname(__file__), 'config_test.ini')