Passion/Python

[Python] ConfigParser

sunshout 2011. 5. 7. 09:23
프로그래밍을 하다 보면 프로그램의 설정파일이 존재하고 이를 파싱하는 일은 귀찮은 일이다.

크게 두가지 형식으로 설정파일이 존재하는데
1) 가장 일반적인 것은
key=value 를 text로 나열하는 것이다.
2) xml 형식으로 설정값을 저장하는 법

텍스트 방식의 설정 파일을 쉽게 파싱해 주는 모듈이 ConfigParser 이다.

설정파일에는
ㅇ Section
    형식: [Section 명]
ㅇ 주석
    형식: ;
ㅇ key=value
   형식:  key=value

[root@cnode09-m-exp ovs-agent]# more agent.ini

;!!edit with caution!!
;(--) -- not show in /etc/init.d/ovs-agent configure

[security]
;ssl support --
;enable ssl support in xmlrpc transport?(enable/disable)
;(be awared if you change this option while agent is running,
;then stop/restart agent must use --force option.)
;(HIDDEN)
ssl=enable
;passwordfile --
;store the username/passwd for ovs-agent basic authentication,
;(HIDDEN)

 
예를 들어 OVM Server의 agent.ini 설정파일의 예이다.


#### 코딩 방법 ####
from ConfigParser  import ConfigParser

config = ConfigParser()
config.read(파일명)

값을 읽는 방법
config.get(섹션명, 옵션명)
ex) config.get("security","ssl")

추가로 값을 설정하는 방법
config.set(섹션명, 옵션명, [값])
ex) config.set("security","ssl","enable")