[Python] 파이썬 config.ini 파일 설정하기, Configparser 사용법
예제
📃config.ini 파일 설정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[DB_CONFIG]
server = 1.121.XX.XX
database = db_name
username = is
password = pw
charset = utf8
[FILES]
sql = SVRXXX_AW_RACK_CHECK_V2.sql
file_directory = Download-SVRXXX
[COVID19]
; FIXME: key until 2024-11-23
encoding_key = iBaAuQXXXXXXXXXXXXXXXXXXXX
decoding_key = iBaAuQXXXXXXXXXXXXXXXXXXXX
[SLACK]
; Bot OAuth Token:xoxb-XXXXXXXXXXXXXXXXXX
bot_token = xoxb-XXXXXXXXXXXXXXXXXXXXXXXX
app_token = C0XXXXXXXXX
channel_id = CXXXXXXXXXX
slack_msg1 = slack_msg
Configparser 사용하여 파일 읽기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import configparser
class SystemInfo:
def get_file_directory():
return (os.path.dirname(os.path.realpath(__file__)))
class ReadConfig:
def __init__(self):
dir = SystemInfo.get_file_directory()
self.conf_file = dir + '\config.ini'
def load_config(self):
if os.path.exists(self.conf_file) == False:
raise Exception('%s file does not exist. \n' % self.conf_file)
else:
config = configparser.ConfigParser()
config.read(self.conf_file, encoding = 'utf-8')
print("Load Config : %s" % self.conf_file)
return config
설정값 가져오기
1
2
3
4
5
6
7
8
9
def main():
config = ReadConfig.load_config(ReadConfig())
# 방법1
SLACK_TOKEN = config.get('SLACK', 'bot_token')
# 방법2
SLACK_TOKEN = config['SLACK']['bot_token']
if __name__ == "__main__":
main()
댓글남기기