【问题标题】:Python: configparser remembers values from previous filesPython:configparser 记住以前文件中的值
【发布时间】:2013-11-21 16:12:11
【问题描述】:

我正在编写一个脚本,它扫描不同目录中的一系列配置文件以确保它们具有特定值:在这种情况下,它们必须具有 MySection 部分,它必须具有选项 @987654322 @,它不能等于 0。如果它通过了所有这些测试,则该文件是 OK 的。

不过,我遇到的问题是 ConfigParser 似乎“记住”了它扫描的所有文件,因此如果它扫描的第一个文件包含 Opt1,则每个后续文件都将测试为 Opt1 为阳性...即使连续的文件是完全空白的。我猜 ConfigParser 有某种缓存需要在读取每个文件之前清除?非常感谢任何帮助。

代码如下:

import configparser
import os
from collections import OrderedDict

parser=configparser.ConfigParser()
parser.optionxform=str

workdir=os.path.dirname(os.path.realpath(__file__))+"/"

def GetAllDirs():
    #Get All Directories in Working Directory
    dirs = [o for o in os.listdir(workdir) if os.path.isdir(os.path.join(workdir,o)) ]
    for d in dirs:
        GetAllTGM(workdir+d)

def GetAllTGM(dir):
    #List all the INI files in a directory
    files= [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
    for f in files:
        fa = dir+"/"+f
        fs = split(fa)
        if fs[1]=='.ini' or fs[1]=='.INI':
            repair(fa,fs)
        else:
            pass

def split(filepath):
    #Split the filepath from the file extension
    return os.path.splitext(filepath)

def getoption(sec,option):
    #Get the value of an option from the file
    return parser.get(sec,option)

def repair(file,fsplit):
    parser.read_file(open(file))
    print("\n"+str(parser.sections()))
    if parser.has_section('MySection'):
    #if section exists
        if parser.has_option('MySection','Opt1'):
        #Check if it has Opt1
            if getoption('MySection','Opt1')=="0":
            #It's bad if Opt1=0
                print("Malformed section in "+str(file))
            else:
            #If Opt1!=0, all is good
                print("Section OK in "+str(file))
        else:
        #It's also bad if Opt1 is not present
            print("Malformed section in "+str(file))
    else:
    #And it's bad if MySection doesn't exist
        print("Section missing from "+str(file))

print("Now Running")
GetAllDirs()

【问题讨论】:

  • 为每个文件创建一个新的解析器对象怎么样?

标签: python configparser


【解决方案1】:

代码多次重复使用相同的 ConfigParser 对象 (parser)。它确实记得配置。

每次读取新文件时创建ConfigParser对象。

def repair(file,fsplit):
    parser = configparser.ConfigParser()
    parser.optionxform = str
    with open(file) as f:
        parser.read_file(f)
    ...

【讨论】:

  • 物有所值!谢谢!
猜你喜欢
  • 2011-02-16
  • 2015-11-05
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多