通过crontab运行时,ConfigParser不会加载部分

问题描述 投票:1回答:2

当我通过命令行运行python脚本时,一切工作都很完美,但是当从cron运行脚本时,ConfigParser会创建一个空的列表列表

me = singleton.SingleInstance()

######### Accessing the configuration file #######################################
config = ConfigParser.RawConfigParser()
config.read('./matrix.cfg')
sections = config.sections()

######### Build the current map ##################################################
print sections

这是cron的工作

* * * * * /usr/bin/python /etc/portmatrix/matrix.py | logger

这是输出

Feb 12 12:59:01 dns01 CRON[30879]: (root) CMD (/usr/bin/python /etc/portmatrix/matrix.py | logger)
Feb 12 12:59:01 dns01 logger: []
python-2.7 configparser
2个回答
2
投票

ConfigParser尝试读取文件./matrix.cfg

现在这个文件的路径是./,这意味着在当前目录中。

那么从cron运行时你对当前目录有什么假设? (我猜你有一个文件/etc/portmatrix/matrix.cfg,你认为./真的意味着“在与运行脚本相同的目录中” - 但这不是真的)

简单的解决方法是提供配置文件的完整路径。例如。:

config = ConfigParser.RawConfigParser()
config.read('/etc/portmatrix/matrix.cfg')

1
投票

我遇到了类似的情况,由于umläute的回答,我能够解决它。

我正在使用操作系统,所以在你的情况下,这将是这样的:

import os
...
base_path = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.RawConfigParser()
config.read(os.path.join(base_path, 'matrix.cfg')
© www.soinside.com 2019 - 2024. All rights reserved.