Configparser有时返回空结果

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

我正在使用Python configparser从ini文件读取配置。 95%的时间,它运行良好。在不对ini文件进行任何更改的情况下(例如,在回归测试过程中),configparser将开始返回空结果,然后在搜索嵌套配置时会出现关键错误。

这表明ini文件没有问题,因为它没有更改,而且还偶尔发生。一旦问题发生,它在配置解析器的所有调用中继续发生,直到我终止程序并重新运行它。

我正在这样读取配置:

try:
    path = os.path.dirname(os.path.realpath(__file__))
    kml_ini = '/'.join([path, 'kml.ini'])
    config = configparser.ConfigParser()
    config.read(kml_ini)
    db_conn_returnable = config['database']['db_connection'].strip()
except Exception as e:
    print(e)        
    traceback.print_exc(file=sys.stdout)
    pprint.pprint(config.sections())
    pprint.pprint({section: dict(config.items(section)) for section in config.sections()})

我遇到错误:getitem中的第959行的文件“ /home/sahmed/anaconda3/envs/kml/lib/python3.6/configparser.py”KeyError:“数据库”

我的ini文件看起来像这样:

[api]
server_debug=False
log_level=info
n_workers=10

[database]
db_connection=http://1.1.1.1:9191
user=admin
pass=whateverman

[cluster]
default_workers=3

我本来以为是一个线程问题,因为我有8个线程不断命中此配置文件(尽管这没有任何意义...我们仅在阅读),所以我什至在阅读器上放了一个紧固件块,仍然没有运气。是什么原因导致这种情况?

python configparser
1个回答
0
投票

我可以用您提供的代码复制问题的唯一方法是,如果我在代码期间强行更改了工作目录。

我将其组合起来以测试问题:

from time import sleep
import configparser
import os

def readINI():
    try:
        path = os.path.dirname(os.path.realpath(__file__))
        ini = '/'.join([path, "test.ini"])
        config = configparser.ConfigParser()
        config.read(ini)
        string = config["things"]["abc"]
        print(string)
    except Exception as e:
        print("Error: {}".format(e))

count = 0
while True:
    count +=1
    readINI()
    sleep(1)
    if count % 3 == 0:
        os.chdir("..")
    elif count > 1 and count % 3 == 1:
        os.chdir("./TestFolder")

test.ini非常简单,只包含两行:

[things]
abc=123

我将两个文件都放在同一个文件夹中,并在“根”文件夹和包含文件的TestFolder之间来回移动。如果您raise异常而不是仅打印异常,那么您将得到相同的错误消息。

[请验证您在执行代码期间没有意外更改工作目录,并查看是否确实是问题的原因。

© www.soinside.com 2019 - 2024. All rights reserved.