ArgumentParser라는 이름에서 부터 알 수 있듯이, argument를 parsing하는 module이다.
python의 standard library에 속해있는 module로 따로 설치할 필요는 없다.
특히 command line에 입력하는 인수(argument)를 구문 분석(parsing)하는 데 쓰인다.
사용법은 다음과 같다.
1. import argparse
2. declare parser
3. add argument
4. parsing the argument
코드와 함께 설명하자면 다음과 같다.
1. import argparse
import os
...
import argparse
...
import numpy as np
2. declare parser
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Description of the program that take the argument")
ArgumentParser 객체
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)
새로운 ArgumentParser 객체를 만듭니다. 모든 매개 변수는 키워드 인자로 전달되어야 합니다. 매개 변수마다 아래에서 더 자세히 설명되지만, 요약하면 다음과 같습니다:
- prog - The name of the program (default: os.path.basename(sys.argv[0]))
- usage - 프로그램 사용법을 설명하는 문자열 (기본값: 파서에 추가된 인자로부터 만들어지는 값)
- description - Text to display before the argument help (by default, no text)
- epilog - Text to display after the argument help (by default, no text)
- parents - ArgumentParser 객체들의 리스트이고, 이 들의 인자들도 포함된다
- formatter_class - 도움말 출력을 사용자 정의하기 위한 클래스
- prefix_chars - 선택 인자 앞에 붙는 문자 집합 (기본값: ‘-‘).
- fromfile_prefix_chars - 추가 인자를 읽어야 하는 파일 앞에 붙는 문자 집합 (기본값: None).
- argument_default - 인자의 전역 기본값 (기본값: None)
- conflict_handler - 충돌하는 선택 사항을 해결하기 위한 전략 (일반적으로 불필요함)
- add_help - 파서에 -h/--help 옵션을 추가합니다 (기본값: True)
- allow_abbrev - 약어가 모호하지 않으면 긴 옵션을 축약할 수 있도록 합니다. (기본값: True)
- exit_on_error - 에러가 발생했을 때 ArgumentParser가 에러 정보로 종료되는지를 결정합니다. (기본값: True)
딥러닝 코드를 기준으로 description 외 기능을 쓰는 코드는 거의 보지 못했다.
3. add argument
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="interpolate for given pair of images")
parser.add_argument("-f0", "--frame0", type=str, required=True,
help="file path of the first input frame")
parser.add_argument("--frame1", type=str, required=True,
help="file path of the second input frame")
declare한 parser에 add_argument를 이용하여 argument를 추가한다.
parser.add_argument()
대표적인 parameter만 정리하자면 다음과 같다.
3-0) name or flags
해당 옵션 문자열의 이름이나 리스트.
e.g., "-f0", "--frame0", "frame"
3-1) dest
"-f0", "--frame0" 에서 "f0"가 dest이다.
즉 name의 shortcut이라고 생각하면 된다.
parser.add_argument("--frame0", dest="f0", type=str, required=True,
help="file path of the first input frame")
위와 같이 dest="f0" 로 따로 설정할 수 도 있다.
3-2) help
description 과 같이 message를 추가하여 argument에 대한 이해를 도울 수 있다.
help='descirption of argument' 와 같은 help message를 추가하면
command linde에서 parser가 선언된 파일과 함께 -h or --help를 입력하면 help message를 보여준다.
3-3) option argument
"-f0" 또는 "--frame0"를 option 인수 라고 한다.
-가 하나만 붙으면 shortcut으로 쓸 수 있으나 프로그램 코드내에서는 정식명칭만 사용할 수 있다.
3-4) required argument
그리고 --가 안 붙어 있으면 필수 인수 라고 한다.
필수 인수는 지정하지 않으면 error가 발생한다.
하지만 위의 예시처럼 옵션인수에 required=True로 선언하여 필수 인수로 사용할 수 있다.
3-5) set default
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="interpolate for given pair of images")
parser.add_argument("-f0", "--frame0", type=str, required=True,
help="file path of the first input frame")
parser.add_argument("--frame1", type=str, required=True,
help="file path of the second input frame")
parser.add_argument("--time_period", type=float, default=0.5,
help="time period for interpolated frame")
위의 예시에서 time_period는 아무것도 입력하지 않으면 기본값으로 0.5가 입력된다.
3-6) specify data type
type=str, int, float 등으로 데이터 형을 지정할 수 있다.
frame의 경우 url을 입력하므로 str형이고, time_period의 경우 실수를 입력하므로 float형이다.
활용법
e.g., '.' 으로 구분된 숫자를 지정한 리스트에서 저장하고 싶은 경우
tp = lambda x:list(map(int, x.split('.')))
parser.add_argument('--address', type=tp, help='IP address')
args = parser.parse_args()
print(args.address)
$ python test.py --address 192.168.31.150
[192, 168, 31, 150]
3-7) action specify how an argument should be handled
parser.add_argument('--flag', action='store_true')
args = parser.parse_args()
print(args.flag)
$ python test.py
False
$ python test.py --flag
True
위의 예시는 해당 인수를 flag로 사용한 것이다.
store_true는 action의 활용법 중 하나로 해당 인수의 입력여부에 따라 True or False로 나타낼 수 있다.
3-8) specify choices
parser.add_argument('--fruit', choices=['apple', 'banana', 'orange'])
인수의 선택지를 지정하여, choices 를 벗어난 값을 입력하면 에러가 발생한다.
3-9) nargs
다수의 argument를 받아서 하나의 action으로 처리하고 싶을 때
parser = argparse.ArgumentParser()
parser.add_argument('--foo', nargs='*')
parser.add_argument('--bar', nargs='*')
parser.add_argument('baz', nargs='*')
parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
add_argument() 메서드
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
단일 명령행 인자를 구문 분석하는 방법을 정의합니다. 매개 변수마다 아래에서 더 자세히 설명되지만, 요약하면 다음과 같습니다:
- name or flags - 옵션 문자열의 이름이나 리스트, 예를 들어 foo 또는 -f, --foo.
- action - 명령행에서 이 인자가 발견될 때 수행 할 액션의 기본형.
- nargs - 소비되어야 하는 명령행 인자의 수.
- const - 일부 action 및 nargs 를 선택할 때 필요한 상숫값.
- default - 인자가 명령행에 없고 namespace 객체에 없으면 생성되는 값.
- type - 명령행 인자가 변환되어야 할 형.
- choices - A sequence of the allowable values for the argument.
- required - 명령행 옵션을 생략 할 수 있는지 아닌지 (선택적일 때만).
- help - 인자가 하는 일에 대한 간단한 설명.
- metavar - 사용 메시지에 사용되는 인자의 이름.
- dest - parse_args() 가 반환하는 객체에 추가될 어트리뷰트의 이름.
4. parsing the argument
앞서 살펴봤지만 마지막으로 이 명령을 해야 argument를 분석합니다.
args = parser.parse_args()
위의 예시처럼 add_argument가 끝난 후 parse_args() 명령을 통해 분석을 실시할 수 도 있으며
parser.parse_args(['XXX'])
이처럼 inline상황에서 명령어를 추가해 줄 수도 있습니다.
출처 : https://docs.python.org/ko/3/library/argparse.html
출처 : https://engineer-mole.tistory.com/213
'데이터 분석 > 딥러닝' 카테고리의 다른 글
Compound Scaling (0) | 2021.11.18 |
---|---|
Optimizer, Loss Funtion (0) | 2021.04.08 |
신경망 학습방법과 역전파(BP) (0) | 2021.04.07 |
Neural Network (0) | 2021.04.06 |