-
[Python] Config Parser 사용법Implementation/Python 2022. 3. 10. 10:39
Create Config Parser
# 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
# 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
Read Config Parser
# 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)) # 3306print(parser.getboolean('settings', 'debug', fallback=False)) # True
Using String Interpolation
# config_file_create.pyfrom 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}' }
${<section name>:<option name>} 형태로 path 잡아주기
# config_file_read.py from configparser import ConfigParser, ExtendedInterpolation parser = ConfigParser(interpolation=ExtendedInterpolation()) parser.read('dev.ini') print(parser.get('files', 'python_path')) # /usr/local/bin/python3
'Implementation > Python' 카테고리의 다른 글
[Python] max 함수에서 key 값 사용하기 (0) 2021.10.27 [Python] tuple(index, key) in list (0) 2021.10.27 [Python] random int list (comprehension list) (0) 2021.09.30 [Python] tensorflow.expand_dims (0) 2021.09.28 [Python] unique key counting dictionary (0) 2021.09.26