Python 구문 분석 구성 모듈의 ConfigParser에 대한 자세한 설명

高洛峰
풀어 주다: 2016-10-18 09:13:10
원래의
1139명이 탐색했습니다.

1. 기본 읽기 구성 파일

-read(filename)은 ini 파일 내용을 직접 읽어

-sections()는 모든 섹션을 가져와서 목록 형식으로 반환합니다

-options(section) 섹션의 모든 옵션을 가져옵니다

-items(section) 섹션의 모든 키-값 쌍을 가져옵니다

-get(section,option ) 섹션 가져오기 섹션의 옵션 값은 문자열 유형으로 반환됩니다.

-getint(section, option) 섹션의 옵션 값을 가져오고 int 유형으로 반환됩니다. 해당 getboolean() 및 getfloat() 함수.

2. 기본 쓰기 구성 파일

-add_section(section) 섹션의 옵션에 새로운 섹션

-set(section, option, value)을 추가하여 설정합니다. , 구성 파일에 콘텐츠를 쓰려면 write를 호출해야 합니다.

3. 기본 예시

test.conf

[sec_a] 
a_key1 = 20 
a_key2 = 10 
   
[sec_b] 
b_key1 = 121 
b_key2 = b_value2 
b_key3 = $r 
b_key4 = 127.0.0.1
로그인 후 복사

parse_test_conf.py

import ConfigParser 
cf = ConfigParser.ConfigParser() 
#read config 
cf.read("test.conf") 
# return all section 
secs = cf.sections() 
print 'sections:', secs 
   
opts = cf.options("sec_a") 
print 'options:', opts 
   
kvs = cf.items("sec_a") 
print 'sec_a:', kvs 
   
#read by type 
str_val = cf.get("sec_a", "a_key1") 
int_val = cf.getint("sec_a", "a_key2") 
   
print "value for sec_a's a_key1:", str_val 
print "value for sec_a's a_key2:", int_val 
   
#write config 
#update value 
cf.set("sec_b", "b_key3", "new-$r") 
#set a new value 
cf.set("sec_b", "b_newkey", "new-value") 
#create a new section 
cf.add_section('a_new_section') 
cf.set('a_new_section', 'new_key', 'new_value') 
   
#write back to configure file 
cf.write(open("test.conf", "w"))
로그인 후 복사

터미널 출력 가져오기:

sections: ['sec_b', 'sec_a'] 
options: ['a_key1', 'a_key2'] 
sec_a: [('a_key1', "i'm value"), ('a_key2', '22')] 
value for sec_a's a_key1: i'm value 
value for sec_a's a_key2: 22
로그인 후 복사

업데이트된 테스트.

[sec_b] 
b_newkey = new-value 
b_key4 = 127.0.0.1 
b_key1 = 121 
b_key2 = b_value2 
b_key3 = new-$r 
   
[sec_a] 
a_key1 = i'm value 
a_key2 = 22 
   
[a_new_section] 
new_key = new_value
로그인 후 복사

4. Python의 ConfigParser 모듈은 INI 파일에서 작동하는 3개의 클래스를 정의합니다. 이들은 각각 RawConfigParser, ConfigParser 및 SafeConfigParser입니다. RawCnfigParser는 가장 기본적인 INI 파일 읽기 클래스입니다. ConfigParser 및 SafeConfigParser는 %(value)s 변수의 구문 분석을 지원합니다.

test2.conf 구성 파일 설정

[portal] 
url = http://%(host)s:%(port)s/Portal 
host = localhost 
port = 8080
로그인 후 복사

RawConfigParser 사용:

import ConfigParser 
  
cf = ConfigParser.RawConfigParser() 
  
print "use RawConfigParser() read" 
cf.read("test2.conf") 
print cf.get("portal", "url") 
  
print "use RawConfigParser() write" 
cf.set("portal", "url2", "%(host)s:%(port)s") 
print cf.get("portal", "url2")
로그인 후 복사

터미널 출력 가져오기:

use RawConfigParser() read 
http://%(host)s:%(port)s/Portal 
use RawConfigParser() write 
%(host)s:%(port)s
로그인 후 복사

대신 ConfigParser 사용:

import ConfigParser 
  
cf = ConfigParser.ConfigParser() 
  
print "use ConfigParser() read" 
cf.read("test2.conf") 
print cf.get("portal", "url") 
  
print "use ConfigParser() write" 
cf.set("portal", "url2", "%(host)s:%(port)s") 
print cf.get("portal", "url2")
로그인 후 복사

터미널 출력 가져오기:

use ConfigParser() read 
http://localhost:8080/Portal 
use ConfigParser() write 
localhost:8080
로그인 후 복사

대신 SafeConfigParser 사용:

import ConfigParser 
  
cf = ConfigParser.SafeConfigParser() 
  
print "use SafeConfigParser() read" 
cf.read("test2.conf") 
print cf.get("portal", "url") 
  
print "use SateConfigParser() write" 
cf.set("portal", "url2", "%(host)s:%(port)s") 
print cf.get("portal", "url2")
로그인 후 복사

터미널 출력 가져오기(효과는 ConfigParser와 동일):

use SafeConfigParser() read 
http://localhost:8080/Portal 
use SateConfigParser() write 
localhost:8080
로그인 후 복사


원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!