Tes*_*rrr 5 cron configparser python-3.x
我有一个简单的python3脚本,当我从控制台运行它时,它可以工作:
import configparser
file = 'config_test.ini'
config = configparser.ConfigParser()
config.read(file)
for key in config['test_section']: print(key)
Run Code Online (Sandbox Code Playgroud)
被调用的ini文件看起来像这样:
[test_section]
testkey1 = 5
testkey2 = 42878180
testkey3 = WR50MS10:1100012307
testkey4 = WR50MS04:1100012010
testkex5 = 192.168.200.168
Run Code Online (Sandbox Code Playgroud)
并且脚本运行正常并返回ini文件的五个键.
不,我每分钟都将它配置为cronjob(在Raspberry Pi上运行rasbian)通过:
* * * * * python3 /home/pi/s0/testconfig.py >> /tmp/cron_debug_log.log 2>&1
Run Code Online (Sandbox Code Playgroud)
并且日志看起来像这样:
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'
Run Code Online (Sandbox Code Playgroud)
有谁知道我做错了亲切的问候
shx*_*hx2 17
从cron运行时,您的脚本在不同的工作目录中运行.这意味着它尝试打开的文件名是相对于不同的目录.
您应该在脚本中使用配置文件的绝对路径.
假设配置文件与您正在运行的脚本位于同一目录中,在python中执行此操作的常用方法是使用__file__内置:
config_file = os.path.join(os.path.dirname(__file__), 'config_test.ini')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5271 次 |
| 最近记录: |