행위

파이썬 config parser

DB CAFE

thumb_up 추천메뉴 바로가기


1 파이썬, ini파일 파서(Config Parser)[편집]

Python Config Parser Config Parser Config Parserkishstats.com

2 Create Config File[편집]

# config_file_create.py
from configparser import ConfigParser
config = ConfigParser()
config['settings'] = {
    'debug': 'true',
    'secret_key': 'abc123',
    'log_path': '/my_app/log'
}

config['db'] = {
    'db_name': 'myapp_dev',
    'db_host': 'localhost',
    'db_port': '8889'
}

config['files'] = {
    'use_cdn': 'false',
    'images_path': '/my_app/images'
}
with open('./dev.ini', 'w') as f:
      config.write(f)

위의 코드를 실행하면 dev.ini 파일이 워킹 디렉토리에 만들어진다.

3 ini 파일 확인[편집]

# dev.ini
[settings]
debug = true
secret_key = abc123
log_path = /my_app/log

[db]
db_name = myapp_dev
db_host = localhost
db_port = 8889

[files]
use_cdn = false
images_path = /my_app/images

4 Read Config File[편집]

# config_file_read.py
from configparser import ConfigParser

parser = ConfigParser()
parser.read('dev.ini')
print(parser.sections())  # ['settings', 'db', 'files']
print(parser.get('settings', 'secret_key'))  # abc123
print(parser.options('settings'))  # ['debug', 'secret_key', 'log_path']
print('db' in parser)  # True
print(parser.get('db', 'db_port'), type(parser.get('db', 'db_port')))  # 8889 <class 'str'>
print(int(parser.get('db', 'db_port')))  # 8889 (as int)
print(parser.getint('db', 'db_default_port', fallback=3306))  # 3306
print(parser.getboolean('settings', 'debug', fallback=False))  # True
sections(): 모든 section 리스트 반환
get(<section_name>,<option_name>): 섹션의 옵션값 str로 반환
getint(),getfloat(),getboolean(): int/float/boolean으로 반환
options(<section_name>):섹션 안의 선택가능한 옵션들반환
in: 섹션 존재 여부 확인

5 Using String Interpolation[편집]

# config_file_create.py
from configparser import ConfigParser
# ...

config['settings'] = {
    'debug': 'true',
    'secret_key': 'abc123',
    'log_path': '/my_app/log',
    'python_version': '3',
    'packages_path': '/usr/local'
}

# ...

config['files'] = {
    'use_cdn': 'false',
    'images_path': '/my_app/images',
    'python_path': '${settings:packages_path}/bin/python${settings:python_version}'
}
  1. ...

config['settings']에 python_version&packages_path를 추가

config['files'] 에 python_path를 추가

여기서 표시 형식은 ${<section name>:<option name>} 형태로 기입

  1. config_file_read.py

from configparser import ConfigParser, ExtendedInterpolation

parser = ConfigParser(interpolation=ExtendedInterpolation()) parser.read('dev.ini')

print(parser.get('files', 'python_path'))

  1. /usr/local/bin/python3

여기서 ExtendedInterpolation 을 추가로 import해준다

ConfigParser(interpolation=ExtendedInterpolation()) 변경