source

Python argparse: 기본값 또는 지정된 값

itover 2022. 11. 21. 22:19
반응형

Python argparse: 기본값 또는 지정된 값

값이 지정되지 않은 플래그만 있는 경우 기본값으로, 사용자가 값을 지정한 경우 기본값 대신 사용자 지정 값을 저장하는 선택적 인수를 사용합니다.이에 대한 조치가 이미 있습니까?

예:

python script.py --example
# args.example would equal a default value of 1
python script.py --example 2
# args.example would equal a default value of 2

액션을 만들 수는 있지만, 이 작업을 수행할 수 있는 기존 방법이 있는지 알아보려고 합니다.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?'0-or-1 인수를 의미합니다.
  • const=1인수가 0인 경우 기본값을 설정합니다.
  • type=int인수를 int로 변환합니다.

네가 원한다면test.py세팅하다example없어도 1로--example를 지정한 후,default=1즉,

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

그리고나서

% test.py 
Namespace(example=1)

차이점:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

그리고.

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

다음과 같습니다.

myscript.py=> 디버깅은 첫 번째 경우 7(디폴트부터), 두 번째 경우 "없음"입니다.

myscript.py --debug=> 디버깅은 각 경우에 1개씩입니다.

myscript.py --debug 2=> 디버깅은 각각2개입니다

언급URL : https://stackoverflow.com/questions/15301147/python-argparse-default-value-or-specified-value

반응형