【问题标题】:ConfigParser does not load sections when run via crontab通过 crontab 运行时,ConfigParser 不加载部分
【发布时间】:2016-02-12 08:59:33
【问题描述】:

当我通过命令行运行 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 |记录器

这是输出

Feb 12 12:59:01 dns01 CRON[30879]: (root) CMD (/usr/bin/python /etc/portmatrix/matrix.py | logger)
2 月 12 日 12:59:01 dns01 记录器:[]

【问题讨论】:

    标签: python-2.7 configparser


    【解决方案1】:

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

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

    那么当从cron 运行时,您对当前目录 做了什么假设? (我猜你有一个文件 /etc/portmatrix/matrix.cfg 并且你假设 ./ 真正的意思是“与运行脚本在同一目录中”——但这不是真的)

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

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

    【讨论】:

      【解决方案2】:

      我遇到了类似的情况,感谢 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')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-29
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        • 2019-11-24
        • 2021-03-14
        • 1970-01-01
        • 2011-08-01
        相关资源
        最近更新 更多