Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3: configparser KeyError when run as Cronjob

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

like image 367
btzs Avatar asked Apr 03 '15 05:04

btzs


1 Answers

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')
like image 186
shx2 Avatar answered Nov 01 '22 22:11

shx2