Python의 argparse에서 동일한 옵션을 여러 번 사용
여러 입력 소스를 받아들이고 각각에 대해 뭔가를하는 스크립트를 작성하려고합니다. 이 같은
./my_script.py \
-i input1_url input1_name input1_other_var \
-i input2_url input2_name input2_other_var \
-i input3_url input3_name
# notice inputX_other_var is optional
그러나 나는 이것을 사용하여 이것을하는 방법을 알 수 없다 argparse
. 각 옵션 플래그를 한 번만 사용할 수 있도록 설정된 것 같습니다. 여러 인수를 단일 옵션 ( nargs='*'
또는 nargs='+'
) 과 연결하는 방법을 알고 있지만 여전히 -i
플래그를 여러 번 사용할 수는 없습니다 . 이 작업을 수행하려면 어떻게해야합니까?
명확하게 말하면 마지막으로 원하는 것은 문자열 목록입니다. 그래서
[["input1_url", "input1_name", "input1_other"],
["input2_url", "input2_name", "input2_other"],
["input3_url", "input3_name"]]
다음은 반복되는 2 인수를 처리하는 파서입니다 metavar
.
parser=argparse.ArgumentParser()
parser.add_argument('-i','--input',action='append',nargs=2,
metavar=('url','name'),help='help:')
In [295]: parser.print_help()
usage: ipython2.7 [-h] [-i url name]
optional arguments:
-h, --help show this help message and exit
-i url name, --input url name
help:
In [296]: parser.parse_args('-i one two -i three four'.split())
Out[296]: Namespace(input=[['one', 'two'], ['three', 'four']])
이것은 2 or 3 argument
사례를 처리하지 않습니다 (예전에는 그러한 범위를 처리하는 Python 버그 / 문제에 대한 패치를 작성했지만).
방법과 별도의 인수 정의에 대한 nargs=3
그리고 metavar=('url','name','other')
?
튜플은 metavar
또한 사용할 수 있습니다 nargs='+'
및 nargs='*'
; 2 개의 문자열은 [-u A [B ...]]
또는 로 사용됩니다 [-u [A [B ...]]]
.
-i
3 개의 인수를 받아들이고 append
작업 을 사용하도록 구성해야합니다 .
>>> p = argparse.ArgumentParser()
>>> p.add_argument("-i", nargs=3, action='append')
_AppendAction(...)
>>> p.parse_args("-i a b c -i d e f -i g h i".split())
Namespace(i=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
선택적 값을 처리하기 위해 간단한 사용자 정의 유형을 사용해 볼 수 있습니다. 이 경우 to 인수 -i
는 분할 수가 2로 제한되는 단일 쉼표로 구분 된 문자열입니다. 값이 두 개 이상 지정되었는지 확인하려면 값을 사후 처리해야합니다.
>>> p.add_argument("-i", type=lambda x: x.split(",", 2), action='append')
>>> print p.parse_args("-i a,b,c -i d,e -i g,h,i,j".split())
Namespace(i=[['a', 'b', 'c'], ['d', 'e'], ['g', 'h', 'i,j']])
For more control, define a custom action. This one extends the built-in _AppendAction
(used by action='append'
), but just does some range checking on the number of arguments given to -i
.
class TwoOrThree(argparse._AppendAction):
def __call__(self, parser, namespace, values, option_string=None):
if not (2 <= len(values) <= 3):
raise argparse.ArgumentError(self, "%s takes 2 or 3 values, %d given" % (option_string, len(values)))
super(TwoOrThree, self).__call__(parser, namespace, values, option_string)
p.add_argument("-i", nargs='+', action=TwoOrThree)
This is simple; just add both action='append'
and nargs='*'
(or '+'
).
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', action='append', nargs='+')
args = parser.parse_args()
Then when you run it, you get
In [32]: run test.py -i input1_url input1_name input1_other_var -i input2_url i
...: nput2_name input2_other_var -i input3_url input3_name
In [33]: args.i
Out[33]:
[['input1_url', 'input1_name', 'input1_other_var'],
['input2_url', 'input2_name', 'input2_other_var'],
['input3_url', 'input3_name']]
ReferenceURL : https://stackoverflow.com/questions/36166225/using-the-same-option-multiple-times-in-pythons-argparse
'IT Share you' 카테고리의 다른 글
AngularJs-SELECT의 ng-model (0) | 2021.01.07 |
---|---|
'x << ~ y'는 JavaScript에서 무엇을 나타 냅니까? (0) | 2021.01.07 |
소품 변경시 React 컴포넌트 다시 렌더링 (0) | 2021.01.07 |
string.Format의 {{{0}}}은 무엇을합니까? (0) | 2021.01.07 |
Javascript에서 비동기 / 대기 병렬 실행 방법 (0) | 2021.01.06 |