Argparse 선택적 위치 인수?
다음과 같이 사용되는 스크립트가 있습니다. usage: installer.py dir [-h] [-v]
dir
다음과 같이 정의되는 위치 인수입니다.
parser.add_argument('dir', default=os.getcwd())
나는 선택 dir
사항이 되기를 원합니다 : 지정되지 않은 경우 cwd
.
불행히도 dir
인수를 지정하지 않으면 Error: Too few arguments
.
사용 nargs='?'
(또는 nargs='*'
둘 이상의 dir이 필요한 경우)
parser.add_argument('dir', nargs='?', default=os.getcwd())
확장 된 예 :
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
@VinaySajip 답변의 확장으로. 언급 할 가치가있는 추가 사항이 있습니다nargs
.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (정수). 명령 줄에서 N 개의 인수가 목록으로 모입니다.
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. 존재하는 모든 명령 줄 인수는 목록으로 수집됩니다. 참고 그것은 일반적으로 더 이상의 위치 인수가 훨씬 이해가되지 않습니다 nargs='*'
만, 여러 선택적 인수가 nargs='*'
가능하다.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. '*'와 마찬가지로 존재하는 모든 명령 줄 인수가 목록으로 수집됩니다. 또한 하나 이상의 명령 줄 인수가없는 경우 오류 메시지가 생성됩니다.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. 나머지 명령 줄 인수는 모두 목록으로 수집됩니다. 이것은 일반적으로 다른 명령 줄 유틸리티에 디스패치하는 명령 줄 유틸리티에 유용합니다.
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
parser.add_argument
also has a switch required. You can use required=False
. Here is a sample snippet with Python 2.7:
parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()
참고URL : https://stackoverflow.com/questions/4480075/argparse-optional-positional-arguments
'developer tip' 카테고리의 다른 글
현재 버전의 ASP.NET MVC를 확인하는 방법은 무엇입니까? (0) | 2020.10.04 |
---|---|
HTML5에 minlength 유효성 검사 속성이 있습니까? (0) | 2020.10.03 |
git 커밋이 어떤 브랜치에서 왔는지 찾기 (0) | 2020.10.03 |
localStorage에 어레이를 어떻게 저장합니까? (0) | 2020.10.03 |
PHP에서 문자열을 숫자로 어떻게 변환합니까? (0) | 2020.10.03 |