最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python configparser中默認(rèn)值的設(shè)定方式

 更新時間:2022年02月10日 17:04:10   作者:Believer007  
這篇文章主要介紹了python configparser中默認(rèn)值的設(shè)定方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

configparser中默認(rèn)值的設(shè)定

在做某一個項(xiàng)目時,在讀配置文件中,當(dāng)出現(xiàn)配置文件中沒有對應(yīng)項(xiàng)目時,如果要設(shè)置默認(rèn)值,以前的做法是如下的:

try:
? ? apple = config.get(section, 'apple')
except NoSectionError, NoOptionError:
? ? apple = None

但當(dāng)存在很多配置時,這種寫法太糟糕

幸好,在Configparser.get()函數(shù)中有一個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

這樣就很好解決了讀取配置文件時沒有option時自動取默認(rèn)值,而不是用rasie的方式取默認(rèn)值

此方案來之stackoverflow

使用configparser的注意事項(xiàng)

以這個非常簡單的典型配置文件為例:

[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ù)會作用于其他Sections

3、數(shù)據(jù)類型

  • config parsers 不會猜測或自動分析識別config.ini參數(shù)的數(shù)據(jù)類型,都會按照字符串類型存儲,如果需要讀取為其他數(shù)據(jù)類型,需要自定義轉(zhuǎn)換。
  • 特殊bool值:對于常見的布爾值’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))添加備注或說明 

[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、寫配置

常見做法:

config.write(open('example.ini', 'w'))

合理做法:

with open('example.ini', 'w') as configfile:
? ? config.write(configfile)

注意要點(diǎn)

1、ConfigParser 在get 時會自動過濾掉‘#’或‘;‘注釋的行(內(nèi)容);

  • 一般情況下我們手工會把配置中的暫時不需要的用‘#‘注釋,問題在于,Configparser 在wirte的時候同file object行為一致,如果將注釋’#‘的配置經(jīng)過get后,再wirte到conf,那么’#‘的配置就會丟失。
  • 那么就需要一個策略或規(guī)則,配置需不需要手工編輯 ?還是建立復(fù)雜的對原生文本的處理的東西,我建議是管住手,避免將一些重要的配置爆露給用戶編輯,切記行內(nèi)注釋和Section內(nèi)注釋。
  • 有一個相對簡單的方法是:
  • 對單獨(dú)在一行的代碼,你可以在讀入前把"#", ";"換成其他字符如’@’,或‘^’(在其bat等其他語言中用的注釋符易于理解),使用allow_no_value選項(xiàng),這樣注釋會被當(dāng)成配置保存下來,處理后你再把“#”, ";"換回來。

2、在ConfigParser write之后,配置文本如果有大寫字母’PRODUCT’會變?yōu)樾懽帜?rsquo;product’,并不影響配置的正確讀寫。 

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python網(wǎng)絡(luò)編程之使用TCP方式傳輸文件操作示例

    Python網(wǎng)絡(luò)編程之使用TCP方式傳輸文件操作示例

    這篇文章主要介紹了Python網(wǎng)絡(luò)編程之使用TCP方式傳輸文件操作,結(jié)合實(shí)例形式分析了使用socket模塊進(jìn)行tcp協(xié)議下文件傳輸?shù)脑硪约胺?wù)器端、客戶端相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2019-11-11
  • 使用Python隨機(jī)生成數(shù)據(jù)的方法

    使用Python隨機(jī)生成數(shù)據(jù)的方法

    這篇文章主要介紹了使用Python隨機(jī)生成數(shù)據(jù)的方法,在日常開發(fā)中竟然會遇到需要測試大量數(shù)據(jù)的地方,那么隨機(jī)生成數(shù)據(jù)就可以有效的加快我們的效率,通過Python_Faker生成測試數(shù)據(jù)需要安裝Faker包,需要的朋友可以參考下
    2023-10-10
  • Python 列表的清空方式

    Python 列表的清空方式

    今天小編就為大家分享一篇Python 列表的清空方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python繪制七彩花朵(用Turtle)

    Python繪制七彩花朵(用Turtle)

    這篇文章主要給大家介紹了關(guān)于Python使用Turtle繪制七彩花朵的相關(guān)資料,通過本文介紹的方法就算剛?cè)腴T的朋友也可以很快的入手繪制出漂亮的七彩花朵,需要的朋友可以參考下
    2023-07-07
  • 計(jì)算pytorch標(biāo)準(zhǔn)化(Normalize)所需要數(shù)據(jù)集的均值和方差實(shí)例

    計(jì)算pytorch標(biāo)準(zhǔn)化(Normalize)所需要數(shù)據(jù)集的均值和方差實(shí)例

    今天小編就為大家分享一篇計(jì)算pytorch標(biāo)準(zhǔn)化(Normalize)所需要數(shù)據(jù)集的均值和方差實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python制作簡單的剪刀石頭布游戲

    Python制作簡單的剪刀石頭布游戲

    這篇文章主要介紹了Python制作剪刀石頭布游戲的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12
  • django fernet fields字段加密實(shí)踐詳解

    django fernet fields字段加密實(shí)踐詳解

    這篇文章主要介紹了django fernet fields字段加密實(shí)踐詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python如何定義接口和抽象類

    Python如何定義接口和抽象類

    這篇文章主要介紹了Python如何定義接口和抽象類,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • Python requests亂碼的五種解決辦法

    Python requests亂碼的五種解決辦法

    在Python中使用requests庫發(fā)送HTTP請求時,有時會遇到亂碼的問題,亂碼通常是由于編碼不一致或解碼錯誤導(dǎo)致的,這篇文章給大家介紹了Python requests亂碼的五種解決辦法,并通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • TF-IDF與余弦相似性的應(yīng)用(一) 自動提取關(guān)鍵詞

    TF-IDF與余弦相似性的應(yīng)用(一) 自動提取關(guān)鍵詞

    這篇文章主要為大家詳細(xì)介紹了TF-IDF與余弦相似性的應(yīng)用,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12

最新評論

和平区| 新宾| 北流市| 富宁县| 松阳县| 英山县| 通榆县| 曲靖市| 新安县| 墨脱县| 夹江县| 黄平县| 灌阳县| 马龙县| 沅江市| 德安县| 瓦房店市| 青岛市| 夏津县| 大埔县| 阿瓦提县| 武宁县| 乌审旗| 梁平县| 赣榆县| 永平县| 绿春县| 进贤县| 玉龙| 惠州市| 逊克县| 大关县| 铜山县| 广汉市| 洛宁县| 黔南| 会同县| 吉木乃县| 云浮市| 竹北市| 固始县|