Python3:当 运行 作为 Cronjob 时,configparser KeyError

Python3: configparser KeyError when run as Cronjob

我有一个简单的 python3 脚本,当我从控制台 运行 时它可以工作:

import configparser

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

调用的 ini 文件如下所示:

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

脚本运行良好,returns ini 文件的五个键。

不,我每分钟将它配置为一个 cronjob(运行 在 rasbian 上 Raspberry Pi)通过:

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

日志如下所示:

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'

有谁知道我做错了什么 亲切的问候

当从 cron 运行 时,您的脚本在不同的 工作目录 中运行。这意味着它试图打开的文件名是相对于另一个目录的。

您应该在脚本中使用配置文件的绝对路径。

在 python 中常见的做法是使用 __file__ builtin:

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