Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 구성 파일 파서(configparser)

<시간/>

Python 표준 라이브러리의 configparser 모듈은 Microsoft Windows OS에서 사용하는 구성 파일을 읽고 쓰는 기능을 정의합니다. 이러한 파일의 확장자는 일반적으로 .INI입니다.

INI 파일은 [섹션] 헤더가 이끄는 섹션으로 구성됩니다. 대괄호 사이에 섹션 이름을 넣을 수 있습니다. 섹션 다음에는 =또는 :문자로 구분된 키/값 항목이 옵니다. 여기에는 # 또는 접두사가 붙은 주석이 포함될 수 있습니다. 상징. 샘플 INI 파일이 아래에 나와 있습니다 -

[Settings]
# Set detailed log for additional debugging info
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
# Sets the location of the MV_FTP log file
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown

[FTP]
# set the FTP server active
RunFTP=1
# defines the FTP control port
FTPPort=21
# Sets the location of the FTP data directory
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
# set the admin Name
UserName=admin
# set the Password
Password=admin

configparser 모듈에는 ConfigParser 클래스가 있습니다. 구성 파일 목록을 구문 분석하고 구문 분석된 데이터베이스를 관리하는 역할을 합니다.

ConfigParser의 개체는 다음 문에 의해 생성됩니다 -

parser = configparser.ConfigParser()

다음 메소드는 이 클래스에 정의되어 있습니다 -

섹션() 모든 구성 섹션 이름을 반환합니다.
has_section() 주어진 섹션이 존재하는지 여부를 반환합니다.
has_option() 주어진 옵션이 주어진 섹션에 존재하는지 여부를 반환합니다.
옵션() 이름이 지정된 섹션에 대한 구성 옵션 목록을 반환합니다.
읽기() 이름이 지정된 구성 파일을 읽고 구문 분석합니다.
read_file() 파일 객체로 제공된 하나의 구성 파일을 읽고 구문 분석합니다.
read_string() 주어진 문자열에서 구성을 읽습니다.
read_dict() 사전에서 구성을 읽습니다. 키는 섹션 이름이고 값은 섹션에 있어야 하는 키와 값이 있는 사전입니다.
get() 명명된 옵션에 대한 문자열 값을 반환합니다.
getint() get()과 비슷하지만 값을 정수로 변환합니다.
getfloat() get()과 비슷하지만 값을 float로 변환합니다.
getboolean() get()과 비슷하지만 값을 부울로 변환합니다. False 또는 True를 반환합니다.
항목() 섹션의 각 옵션에 대해 (이름, 값)이 있는 튜플 목록을 반환합니다.
remove_section() 주어진 파일 섹션과 모든 옵션을 제거합니다.
remove_option() 지정된 섹션에서 지정된 옵션을 제거합니다.
set() 주어진 옵션을 설정합니다.
쓰기() 구성 상태를 .ini 형식으로 작성합니다.

다음 스크립트는 'sampleconfig.ini' 파일을 읽고 구문 분석합니다.

import configparser
parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')
for sect in parser.sections():
   print('Section:', sect)
   for k,v in parser.items(sect):
      print(' {} = {}'.format(k,v))
   print()

출력

Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown

Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin

write() 메서드는 구성 파일을 만드는 데 사용됩니다. 다음 스크립트는 파서 개체를 구성하고 'test.ini'를 나타내는 파일 개체에 씁니다.

import configparser
parser = configparser.ConfigParser()
parser.add_section('Manager')
parser.set('Manager', 'Name', 'Ashok Kulkarni')
parser.set('Manager', 'email', 'ashok@gmail.com')
parser.set('Manager', 'password', 'secret')
fp=open('test.ini','w')
parser.write(fp)
fp.close()