当 运行 通过 crontab 时,ConfigParser 不加载部分
ConfigParser does not load sections when run via crontab
当我通过命令行 运行 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: []
ConfigParser 尝试读取文件 ./matrix.cfg
。
现在这个文件的路径是./
,也就是说在当前目录。
那么当您从 cron
变成 运行 时,您对 当前目录 做了什么假设? (我猜你有一个文件 /etc/portmatrix/matrix.cfg
并且你假设 ./
真的意味着“ 在与 运行ning 脚本 相同的目录中” - 这个然而事实并非如此)
简单的修复方法是提供配置文件的完整 路径。例如:
config = ConfigParser.RawConfigParser()
config.read('/etc/portmatrix/matrix.cfg')
我 运行 遇到了类似的情况,感谢 umläute 的回答,我得以解决。
不过,我使用的是 os,因此在您的情况下,这类似于:
import os
...
base_path = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.RawConfigParser()
config.read(os.path.join(base_path, 'matrix.cfg')
当我通过命令行 运行 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: []
ConfigParser 尝试读取文件 ./matrix.cfg
。
现在这个文件的路径是./
,也就是说在当前目录。
那么当您从 cron
变成 运行 时,您对 当前目录 做了什么假设? (我猜你有一个文件 /etc/portmatrix/matrix.cfg
并且你假设 ./
真的意味着“ 在与 运行ning 脚本 相同的目录中” - 这个然而事实并非如此)
简单的修复方法是提供配置文件的完整 路径。例如:
config = ConfigParser.RawConfigParser()
config.read('/etc/portmatrix/matrix.cfg')
我 运行 遇到了类似的情况,感谢 umläute 的回答,我得以解决。
不过,我使用的是 os,因此在您的情况下,这类似于:
import os
...
base_path = os.path.dirname(os.path.realpath(__file__))
config = ConfigParser.RawConfigParser()
config.read(os.path.join(base_path, 'matrix.cfg')