티스토리 뷰

import argparse

 

기본 설정

parser = argparse.ArgumentParser(description='✨')
parser.add_argument('--lr', default=0.1, type=float, help='learning_rate')

...

args = parser.parse_args()

 

이렇게 써주면 끝인데

 

choice를 추가해주는 방법

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

 

만약 인자로 여러 value들을 받고싶다면?

parser.add_argument('-i', '--item', action='store', dest='alist',
                    type=str, nargs='*', default=['item1', 'item2', 'item3'],
                    help="Examples: -i item1 item2, -i item3")



print("List of items: {}".format(opts.alist))

python3.6 temp_agrs1.py -i item5 item6 item7
List of items: ['item5', 'item6', 'item7']

python3.6 temp_agrs1.py -i item10
List of items: ['item10']

python3.6 temp_agrs1.py
List of items: ['item1', 'item2', 'item3']

 

"type=list option. Don't use that. That turns a string into a list, and hence the lists of lists."

 

nargs 쓰기

 

I use nargs='*' as an add_argument parameter. I specifically used nargs='*' to the option to pick defaults if I am not passing any explicit arguments

 

 

parse된 인자 받아오기

parser = argparse.ArgumentParser(description='✨Welcome to YourBench-Adversarial Attack Robustness Benchmarking & Reporting tools.✨')
parser.add_argument('--attack_method', required=True, type=str, nargs='*', choices=['FGSM', 'CW'], dest='parsedAttackMethod', action='append')
parser.add_argument('--model', required=True, type=str, choices=['WRN', 'ResNet18'], dest='parsedModel')
parser.add_argument('--dataset', required=True, type=str, choices=['CIFAR-10', 'CIFAR-100', 'ImageNet'], dest='parsedDataset')

args = parser.parse_args()
print(args.parsedAttackMethod)
print(args.parsedModel)
print(args.parsedDataset)

 

필수 인자?

positional 인자와 optional 인자가 있다. 인자의 이름 앞에 -가 붙어 있으면 optional, 아니면 positional 인자로서 필수로 지정해야 한다.
단, positional 인자도 필수로 넣어야 하게끔 할 수 있다. add_argument() 함수에 required=True를 집어넣으면 된다. 그러나 C언어에서 #define true false같은 짓인 만큼 권장되지 않는다.

 

default에 os.environ.get('', '') 추가하기

parser.add_argument('--model_dir', type=str, default=os.environ.get('SM_CHANNEL_MODEL', './model/exp'))

 

 

⭐️action의 종류 지정

인자를 정의(add_argument()에 의해)할 때 action을 지정할 수 있다. 액션에는 다음과 같은 것들이 있으며, 기본값은 store이다.

  • store: action을 지정하지 않으면 store이 된다. 인자 이름 바로 뒤의 값을 해당 인자에 대입(저장)시킨다.
  • store_const: add_argument()에서 미리 지정되어 있는 const=에 해당하는 값이 저장된다. const=는 반드시 써 주어야 한다.
  • store_true, store_false: 인자를 적으면(값은 주지 않는다) 해당 인자에 True나 False가 저장된다.
  • append: 값을 하나가 아닌 여러 개를 저장하고 싶을 때 쓴다. 인자를 여러 번 호출하면 같이 주는 값이 계속 append된다.
  • append_const: append와 비슷하지만 사전에 지정한 const 값이 저장된다.
  • count: 인자를 적은 횟수만큼 값이 올라간다. 보통 verbose 옵션에 많이 쓴다.
  • help: 도움말 메시지를 출력하게 하고 종료하여 코드는 실행시키지 않는다. --help 역할을 대신한다.
  • version: version 인자에 사용가능하다. 버전 정보를 출력하고 종료한다.

 

argv를 쓰는 방법

argparse를 쓰는 방법이 고오급이라면 argv를 쓰는 방법은 상대적으로 간단하고 명료하다. 

from sys import argv
print(argv)

이러면 파일명이 argv[0], 그 뒤 인자들이 argv[1],,, 순으로 들어간다. 

 

 

출처

https://greeksharifa.github.io/references/2019/02/12/argparse-usage/#dest-적용-위치-지정

https://stackoverflow.com/questions/15753701/how-can-i-pass-a-list-as-a-command-line-argument-with-argparse

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함