溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python項(xiàng)目中利用ConfigParser如何實(shí)現(xiàn)讀取配置文件

發(fā)布時(shí)間:2020-11-16 15:32:42 來(lái)源:億速云 閱讀:122 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了Python項(xiàng)目中利用ConfigParser如何實(shí)現(xiàn)讀取配置文件,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

在項(xiàng)目過(guò)程中,需要設(shè)置各種IP和端口號(hào)信息等,如果每次都在源程序中更改會(huì)很麻煩(因?yàn)槊看味家貑㈨?xiàng)目重新加載配置信息),因此將需要修改的參數(shù)寫在配置文件(或者數(shù)據(jù)庫(kù))中,每次只需修改配置文件,就可以實(shí)現(xiàn)同樣的目的。Python 標(biāo)準(zhǔn)庫(kù)的 ConfigParser 模塊提供一套 API 來(lái)讀取和操作配置文件。因此在程序開始位置要導(dǎo)入該模塊,注意區(qū)分是python2還是python3,python3有一些改動(dòng)

import ConfigParser #python 2.x
import configparser #python 3.x

配置文件的格式

  • a) 配置文件中包含一個(gè)或多個(gè) section, 每個(gè) section 有自己的 option;
  • b) section 用 [sect_name] 表示,每個(gè)option是一個(gè)鍵值對(duì),使用分隔符 = 或 : 隔開;
  • c) 在 option 分隔符兩端的空格會(huì)被忽略掉
  • d) 配置文件使用 # 和 ; 注釋
     

一個(gè)簡(jiǎn)單的配置文件樣例 config.conf

# database source
[db]   # 對(duì)應(yīng)的是一個(gè)section
host = 127.0.0.1  # 對(duì)應(yīng)的是一個(gè)option鍵值對(duì)形式
port = 3306
user = root
pass = root
 
# ssh
[ssh]
host = 192.168.10.111
user = sean
pass = sean

ConfigParser 的基本操作

a) 實(shí)例化 ConfigParser 并加載配置文件

cp = ConfigParser.SafeConfigParser()
cp.read('config.conf')

b) 獲取 section 列表、option 鍵列表和 option 鍵值元組列表

print('all sections:', cp.sections()) # sections: ['db', 'ssh']
print('options of [db]:', cp.options('db')) # options of [db]: ['host', 'port', 'user', 'pass']
print('items of [ssh]:', cp.items('ssh')) # items of [ssh]: [('host', '192.168.10.111'), ('user', 'sean'), ('pass', 'sean')]

c) 讀取指定的配置信息

print('host of db:', cp.get('db', 'host')) # host of db: 127.0.0.1
print('host of ssh:', cp.get('ssh', 'host')) # host of ssh: 192.168.10.111

d) 按類型讀取配置信息:getint、 getfloat 和 getboolean

print(type(cp.getint('db', 'port'))) # <type 'int'>

e) 判斷 option 是否存在

print(cp.has_option('db', 'host')) # True  

f) 設(shè)置 option

cp.set('db', 'host','192.168.10.222')

g) 刪除 option

cp.remove_option('db', 'host')

h) 判斷 section 是否存在

print(cp.has_section('db')) # True

i) 添加 section

cp.add_section('new_sect')

j) 刪除 section

cp.remove_section('db')

k) 保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不會(huì)修改配置文件,write 方法可以將 ConfigParser 對(duì)象的配置寫到文件中

cp.write(open('config.conf', 'w'))
cp.write(sys.stdout)

上述內(nèi)容就是Python項(xiàng)目中利用ConfigParser如何實(shí)現(xiàn)讀取配置文件,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI