【问题标题】:cronjob not able to access config.ini when running python3 script运行 python3 脚本时,cronjob 无法访问 config.ini
【发布时间】:2020-11-20 02:52:46
【问题描述】:

我有一个运行 python3 脚本的 crontab 条目。这个 python 脚本使用一个 config.ini 文件来获取一些在脚本中使用的令牌。

crontab 条目是:

*/15 * * * * /usr/bin/python3 /opt/scripts/tf_state_backup/tf_state_backup.py >> ~/cron.out 2>&1

config.ini 文件有以下内容:

[terraform]
token = <base64 encoded API key>

[gitlab]
token = <base64 encoded API key>

python脚本的相关部分如下:

import configparser

## read config file and decode api keys
config = configparser.ConfigParser()
config.read(os.path.abspath('config.ini'))

tfc_token = base64.b64decode(config['terraform']['token']).decode('utf-8')
gitlab_token = base64.b64decode(config['gitlab']['token']).decode('utf-8')

当它运行时,我可以检查 cron.out 文件是否有任何错误。每次运行时都会出现以下错误。

SyntaxError: invalid syntax
Traceback (most recent call last):
  File "/opt/scripts/tf_state_backup/tf_state_backup.py", line 17, in <module>
    tfc_token = base64.b64decode(config['terraform']['token']).decode('utf-8')
  File "/usr/lib64/python3.6/configparser.py", line 959, in __getitem__
    raise KeyError(key)
KeyError: 'terraform'

我已经检查了以下内容:

  • 确保脚本和配置具有正确的权限和 +x 权限
  • 完全按照 cron 选项卡中的方式运行脚本,它运行良好,没有任何问题
  • 确保 config.ini 被它的绝对路径引用,而不是相对路径

在这方面的任何帮助都会非常好。

【问题讨论】:

    标签: python-3.x cron configparser


    【解决方案1】:

    您应该使用ConfigParser 对象的get 方法。第一个参数是节名,第​​二个是变量名。如果 raw 参数设置为 True 则特殊字符将被读取为字符串(例如:%)。

    我已经写了一个工作版本。

    test.ini:

    [terraform]
    token = aGVsbG93b3JsZA==
    
    [gitlab]
    token = bm90X2hlbGxvd29ybGQ=
    

    test.py:

    import configparser
    import base64
    
    config = configparser.ConfigParser()
    config.read("test.ini")
    
    tfc_token = base64.b64decode(config.get('terraform', 'token', raw=True)).decode('utf-8')
    gitlab_token = base64.b64decode(config.get('gitlab', 'token', raw=True)).decode('utf-8')
    
    print(tfc_token)
    print(gitlab_token)
    

    输出:

    >>> python3 test.py 
    helloworld
    not_helloworld
    

    仅供参考:

    【讨论】:

      【解决方案2】:

      我设法通过将 cron 作业更新为以下内容来运行它:

      */15 * * * * cd /opt/scripts/tf_state_backup/ && /usr/bin/python3 /opt/scripts/tf_state_backup/tf_state_backup.py
      

      我可能没有正确获取配置文件的路径?

      不管它现在是否正常工作。

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 1970-01-01
        • 2021-02-13
        • 2017-10-20
        • 1970-01-01
        • 2021-09-04
        • 2021-08-19
        • 1970-01-01
        • 2015-06-08
        相关资源
        最近更新 更多