網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
configparser中默認(rèn)值的設(shè)定
在做某一個(gè)項(xiàng)目時(shí),在讀配置文件中,當(dāng)出現(xiàn)配置文件中沒(méi)有對(duì)應(yīng)項(xiàng)目時(shí),如果要設(shè)置默認(rèn)值,以前的做法是如下的:
try: ? ? apple = config.get(section, 'apple') except NoSectionError, NoOptionError: ? ? apple = None
但當(dāng)存在很多配置時(shí),這種寫法太糟糕
幸好,在Configparser.get()函數(shù)中有一個(gè)vars()的參數(shù),可以自定義;注:只能用ConfigParser.ConfigParser;rawconfigparser是不支持的
解決方案
1、定義函數(shù):
class DefaultOption(dict): ? ? def __init__(self, config, section, **kv): ? ? ? ? self._config = config ? ? ? ? self._section = section ? ? ? ? dict.__init__(self, **kv) ? ? def items(self): ? ? ? ? _items = [] ? ? ? ? for option in self: ? ? ? ? ? ? if not self._config.has_option(self._section, option): ? ? ? ? ? ? ? ? _items.append((option, self[option])) ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? value_in_config = self._config.get(self._section, option) ? ? ? ? ? ? ? ? _items.append((option, value_in_config)) ? ? ? ? return _items
2、使用
def read_config(section, location): ? ? config = configparser.ConfigParser() ? ? config.read(location) ? ? apple = config.get(section, 'apple', ? ? ? ? ? ? ? ? ? ? ? ?vars=DefaultOption(config, section, apple=None)) ? ? pear = config.get(section, 'pear', ? ? ? ? ? ? ? ? ? ? ? vars=DefaultOption(config, section, pear=None)) ? ? banana = config.get(section, 'banana', ? ? ? ? ? ? ? ? ? ? ? ? vars=DefaultOption(config, section, banana=None)) ? ? return apple, pear, banana
這樣就很好解決了讀取配置文件時(shí)沒(méi)有option時(shí)自動(dòng)取默認(rèn)值,而不是用rasie的方式取默認(rèn)值
此方案來(lái)之stackoverflow
使用configparser的注意事項(xiàng)
以這個(gè)非常簡(jiǎn)單的典型配置文件為例:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
1、config parser 操作跟dict 類似,在數(shù)據(jù)存取方法基本一致
>> import configparser >>> config = configparser.ConfigParser() >>> config.sections() [] >>> config.read('example.ini') ['example.ini'] >>> config.sections() ['bitbucket.org', 'topsecret.server.com'] >>> 'bitbucket.org' in config True >>> 'bytebong.com' in config False >>> config['bitbucket.org']['User'] 'hg' >>> config['DEFAULT']['Compression'] 'yes' >>> topsecret = config['topsecret.server.com'] >>> topsecret['ForwardX11'] 'no' >>> topsecret['Port'] '50022' >>> for key in config['bitbucket.org']: print(key) ... user compressionlevel serveraliveinterval compression forwardx11 >>> config['bitbucket.org']['ForwardX11'] 'yes'
2、默認(rèn)配置項(xiàng)[DEFAULT]section 的默認(rèn)參數(shù)會(huì)作用于其他Sections
3、數(shù)據(jù)類型
- config parsers 不會(huì)猜測(cè)或自動(dòng)分析識(shí)別config.ini參數(shù)的數(shù)據(jù)類型,都會(huì)按照字符串類型存儲(chǔ),如果需要讀取為其他數(shù)據(jù)類型,需要自定義轉(zhuǎn)換。
- 特殊bool值:對(duì)于常見(jiàn)的布爾值’yes’/‘no’, ‘on’/‘off’, ‘true’/‘false’ 和 ‘1’/‘0’,提供了getboolean()方法。
4、獲取參數(shù)值方法 get()
- 使用get()方法獲取每一參數(shù)項(xiàng)的配置值。
- 如果一般Sections 中參數(shù)在[DEFAULT]中也有設(shè)置,則get()到位[DEFAULT]中的參數(shù)值。
5、參數(shù)分隔符可以使用‘=’或‘:’(默認(rèn))
6、可以使用‘#’或‘;’(默認(rèn))添加備注或說(shuō)明?
[Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?
7、寫配置
常見(jiàn)做法:
config.write(open('example.ini', 'w'))
合理做法:
with open('example.ini', 'w') as configfile: ? ? config.write(configfile)
注意要點(diǎn)
1、ConfigParser 在get 時(shí)會(huì)自動(dòng)過(guò)濾掉‘#’或‘;‘注釋的行(內(nèi)容);
- 一般情況下我們手工會(huì)把配置中的暫時(shí)不需要的用‘#‘注釋,問(wèn)題在于,Configparser 在wirte的時(shí)候同file object行為一致,如果將注釋’#‘的配置經(jīng)過(guò)get后,再wirte到conf,那么’#‘的配置就會(huì)丟失。
- 那么就需要一個(gè)策略或規(guī)則,配置需不需要手工編輯 ?還是建立復(fù)雜的對(duì)原生文本的處理的東西,我建議是管住手,避免將一些重要的配置爆露給用戶編輯,切記行內(nèi)注釋和Section內(nèi)注釋。
- 有一個(gè)相對(duì)簡(jiǎn)單的方法是:
- 對(duì)單獨(dú)在一行的代碼,你可以在讀入前把"#", ";"換成其他字符如’@’,或‘^’(在其bat等其他語(yǔ)言中用的注釋符易于理解),使用allow_no_value選項(xiàng),這樣注釋會(huì)被當(dāng)成配置保存下來(lái),處理后你再把“#”, ";"換回來(lái)。
2、在ConfigParser write之后,配置文本如果有大寫字母’PRODUCT’會(huì)變?yōu)樾懽帜浮痯roduct’,并不影響配置的正確讀寫。?
原文鏈接:https://www.cnblogs.com/landhu/p/9456095.html
相關(guān)推薦
- 2022-12-15 Go字典使用詳解_Golang
- 2022-12-05 Spark中的數(shù)據(jù)讀取保存和累加器實(shí)例詳解_相關(guān)技巧
- 2022-05-11 使用Redission實(shí)現(xiàn)分布式鎖
- 2022-06-22 Android使用EventBus多次接收消息_Android
- 2022-03-22 C++類的定義與實(shí)現(xiàn)_C 語(yǔ)言
- 2022-03-15 feign.RetryableException: Read timed out executing
- 2022-09-19 Android簡(jiǎn)單實(shí)現(xiàn)菜單拖拽排序的功能_Android
- 2022-01-30 Unknown custom element: <router-view> - did you re
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支