네이버 Boostcamp AI tech 4기

실행프로그램의 설정값 입력받는 방법 (configparse, argparser)

애둥 2022. 10. 27. 23:36

1. configparser

  • 프로그램의 실행 설정을 file에 저장
  • Section, Key, Value 값의 형태로 설정된 설정 파일을 사용
  • 설정 파일을 Dict Type으로 호출 후 사용

    config file (확장자 .cfg)

[SectionOne]    # Section - 대괄호 
Status: Single    # 속성 - Key : Value
Name: Derek
Value: Yes
Age: 30

[SectionTwo]
FavoriteColor = Green    # :(콜론)을 써도 되고, =(equal)을 써도 된다. 

[SectionThree]
FamilyName: Johnson

    configparser.py

import configparser
config = configparser.ConfigParser()
config.sections()   # 빈 List

config.read('example.cfg')
config.sections()   # Section Name들 List

for sec in config.sections():
    print(f'---{sec}---')
    for key in config[sec]:
        value = config[sec][key]
        print('{0} : {1}'.format(key, value))

2. argparser

  • Console 창에서 프로그램 실행시 Setting 정보를 저장
  • 거의 모든 Consol 기반 Python 프로그램에서 기본으로 제공
  • 특수 모듈도 많이 존재하지만, 일반적으로 argparse 사용
  • Command-Line Option 이라고 부른다.

reference : https://docs.python.org/3/library/argparse.html

    example_argparse.py

import argparse

# Parser
parser = argparse.ArgumentParser()

# add_argument('-짧은이름', '-긴이름', type="데이터타입", default="디폴트값", help="help 설명")
parser.add_argument('-a', '--a_value', type=int, default=0, help='A integer value (default:0)')
parser.add_argument('-b', '--b_value', type=int, default=0, help='B integer value (default:0)')

args = parser.parse_args()

print(args)
print(args.a_value)
print(args.b_value)

# 실행
a = args.a_value
b = args.b_value
out = a+b
print(out)