欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python configparser中默認值的設定方式

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

configparser中默認值的設定

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

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

但當存在很多配置時,這種寫法太糟糕

幸好,在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時自動取默認值,而不是用rasie的方式取默認值

此方案來之stackoverflow

使用configparser的注意事項

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

[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、默認配置項[DEFAULT]section 的默認參數(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ù)項的配置值。
  • 如果一般Sections 中參數(shù)在[DEFAULT]中也有設置,則get()到位[DEFAULT]中的參數(shù)值。

5、參數(shù)分隔符可以使用‘=’或‘:’(默認)

6、可以使用‘#’或‘;’(默認)添加備注或說明 

[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)

注意要點

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

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

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

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

相關文章

  • 修復 Django migration 時遇到的問題解決

    修復 Django migration 時遇到的問題解決

    本篇文章主要介紹了修復 Django migration 時遇到的問題解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • python處理emoji表情(兩個函數(shù)解決兩者之間的聯(lián)系)

    python處理emoji表情(兩個函數(shù)解決兩者之間的聯(lián)系)

    這篇文章主要介紹了python處理emoji表情,主要通過兩個函數(shù)解決兩者之間的聯(lián)系,本文通過實例代碼給大家介紹的非常完美,對python emoji表情的相關知識感興趣的朋友一起看看吧
    2021-05-05
  • 使用pyinstaller逆向.pyc文件

    使用pyinstaller逆向.pyc文件

    這篇文章主要介紹了使用pyinstaller逆向.pyc文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • Django單元測試工具test client使用詳解

    Django單元測試工具test client使用詳解

    這篇文章主要介紹了Django單元測試工具test client使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08
  • Python語言內(nèi)置數(shù)據(jù)類型

    Python語言內(nèi)置數(shù)據(jù)類型

    這篇文章主要介紹了Python語言中數(shù)據(jù)類型支持得運算符,Python語言提供了豐富的內(nèi)置數(shù)據(jù)類型。用于有效的處理各種類型的數(shù)據(jù),下文將介紹到其數(shù)據(jù)類型支持的運算符等相關內(nèi)容,需要的朋友可以參考一下
    2022-02-02
  • 使用Python統(tǒng)計代碼運行時間的兩種方法

    使用Python統(tǒng)計代碼運行時間的兩種方法

    有時候我們需要記錄一個程序運行的時間,下面這篇文章主要給大家介紹了關于使用Python統(tǒng)計代碼運行時間的兩種方法,文中通過圖文以及示例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-12-12
  • python數(shù)據(jù)分析之文件讀取詳解

    python數(shù)據(jù)分析之文件讀取詳解

    大家好,本篇文章主要講的是python數(shù)據(jù)分析之文件讀取詳解,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • 計算Python Numpy向量之間的歐氏距離實例

    計算Python Numpy向量之間的歐氏距離實例

    這篇文章主要介紹了計算Python Numpy向量之間的歐氏距離實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python讀寫Excel文件方法介紹

    Python讀寫Excel文件方法介紹

    這篇文章主要介紹了Python讀寫Excel文件方法介紹,本文講解了xlrd、xlwt、xlutils等類庫的使用,需要的朋友可以參考下
    2014-11-11
  • 如何使用PyTorch實現(xiàn)自由的數(shù)據(jù)讀取

    如何使用PyTorch實現(xiàn)自由的數(shù)據(jù)讀取

    這篇文章主要給大家介紹了關于如何使用PyTorch實現(xiàn)自由的數(shù)據(jù)讀取的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2022-03-03

最新評論