본문 바로가기
파이썬

파이썬 Python argparse 상호 배타적 그룹

by º기록 2021. 1. 12.
반응형

내가 필요한 것은 :

pro [-a xxx | [-b yyy -c zzz]]

나는 이것을 시도했지만 작동하지 않습니다. 누군가 나를 도울 수 있습니까?

group= parser.add_argument_group('Model 2')
group_ex = group.add_mutually_exclusive_group()
group_ex.add_argument("-a", type=str, action = "store", default = "", help="test")
group_ex_2 = group_ex.add_argument_group("option 2")
group_ex_2.add_argument("-b", type=str, action = "store", default = "", help="test")
group_ex_2.add_argument("-c", type=str, action = "store", default = "", help="test")

감사!

 

해결 방법

 

add_mutually_exclusive_group 은 전체 그룹을 상호 배타적으로 만들지 않습니다. 그룹 내의 옵션을 상호 배타적으로 만듭니다.


prog 
  command 1 
    -a: ...
  command 2
    -b: ...
    -c: ...

첫 번째 인수 세트로 호출하려면 다음을 수행하십시오.

prog command_1 -a xxxx

두 번째 인수 세트를 사용하여 호출하려면 다음을 수행하십시오.

prog command_2 -b yyyy -c zzzz

하위 명령 인수를 위치로 설정할 수도 있습니다.

prog command_1 xxxx

git 또는 svn과 같은 종류 :

git commit -am
git merge develop
# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', action='store_true', help='help for foo arg.')
subparsers = parser.add_subparsers(help='help for subcommand')

# create the parser for the "command_1" command
parser_a = subparsers.add_parser('command_1', help='command_1 help')
parser_a.add_argument('a', type=str, help='help for bar, positional')

# create the parser for the "command_2" command
parser_b = subparsers.add_parser('command_2', help='help for command_2')
parser_b.add_argument('-b', type=str, help='help for b')
parser_b.add_argument('-c', type=str, action='store', default='', help='test')
>>> parser.print_help()
usage: PROG [-h] [--foo] {command_1,command_2} ...

positional arguments:
  {command_1,command_2}
                        help for subcommand
    command_1           command_1 help
    command_2           help for command_2

optional arguments:
  -h, --help            show this help message and exit
  --foo                 help for foo arg.
>>>

>>> parser.parse_args(['command_1', 'working'])
Namespace(a='working', foo=False)
>>> parser.parse_args(['command_1', 'wellness', '-b x'])
usage: PROG [-h] [--foo] {command_1,command_2} ...
PROG: error: unrecognized arguments: -b x

행운을 빕니다.

 

참조 페이지 https://stackoverflow.com/questions/17909294

 

 

반응형

댓글