簡體   English   中英

Python ConfigParser:如何計算在特定部分中設置的選項(而不是默認值)

[英]Python ConfigParser: how to work out options set in a specific section (rather than defaults)

我有一個使用標准ConfigParser庫中的RawConfigParser讀取的配置文件。 我的配置文件有一個[DEFAULT]部分,然后是[specific]部分。 當我循環瀏覽[specific]部分中的選項時,它包括[DEFAULT]下的選項,這就是要發生的情況。

但是,對於報告,我想知道是在[特定]部分還是[默認]中設置了該選項。 是否可以通過RawConfigParser的接口來執行此操作,或者我只能手動解析文件,所以別無選擇嗎? (我已經尋找了一點,我開始擔心最糟糕的事情...)

例如

[默認]

名稱= a

姓= b

[部分]

名稱= b

年齡= 23

您如何使用RawConfigParser界面從[DEFAULT]部分或[SECTION]部分中加載選項名稱和姓氏?

(我知道[DEFAULT]適用於所有對象,但您可能希望在內部報告類似的內容,以便通過復雜的配置文件進行操作)

謝謝!

我最近通過將選項制作成字典,然后合並字典來做到這一點。 整潔的是,用戶參數會覆蓋默認值,並且很容易將它們全部傳遞給函數。

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')

defaultparam = {k:v for k,v in config.items('DEFAULT')}
userparam = {k:v for k,v in config.items('Section 1')}

mergedparam = dict(defaultparam.items() + userparam.items())

給定此配置文件:

[DEFAULT]
name = a
surname = b

[Section 1]
name  = section 1 name
age = 23
#we should get a surname value from defaults

[Section 2]
name = section 2 name
surname = section 2 surname
age = 24

這是一個可以理解第1節正在使用默認姓氏屬性的程序。

import ConfigParser

parser = ConfigParser.RawConfigParser()
parser.read("config.ini")
#Do your normal config processing here
#When it comes time to audit default vs. explicit,
#clear the defaults
parser._defaults = {}
#Now you will see which options were explicitly defined
print parser.options("Section 1")
print parser.options("Section 2")

這是輸出:

['age', 'name']
['age', 'surname', 'name']

RawConfigParser.has_option(section, option)完成這項工作嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM