是否可以在python中分组args?这是一个带有argparse的MWE:
#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser()
# group 1:
parser.add_argument('-a', '--aa',
help = "option a",
dest = 'a',
action = 'store',
)
parser.add_argument('-b', '--bb',
help = "option b",
dest = 'b',
action = 'store',
)
# group 2:
parser.add_argument('-c', '--cc',
help = "option c",
dest = 'c',
action = 'store',
)
parser.add_argument('-d', '--dd',
help = "option d",
dest = 'd',
action = 'store',
)
# last group:
parser.add_argument('--version', action='version', version='%(prog)s 0.1')
args = parser.parse_args()
这给出了:
./test02.py -h
usage: test02.py [-h] [-a A] [-b B] [-c C] [-d D] [--version]
optional arguments:
-h, --help show this help message and exit
-a A, --aa A option a
-b B, --bb B option b
-c C, --cc C option c
-d D, --dd D option d
--version show program's version number and exit
虽然我想:
./test02.py -h
usage: test02.py [-h] [-a A] [-b B] [-c C] [-d D] [--version]
optional arguments:
-h, --help show this help message and exit
--version show program's version number and exit
group 1:
-a A, --aa A option a
-b B, --bb B option b
group 2:
-c C, --cc C option c
-d D, --dd D option d
答案 0 :(得分:4)
由于您只希望这些组影响帮助显示,argument groups
应该可以解决问题:
https://docs.python.org/3/library/argparse.html#argument-groups
parser = argparse.ArgumentParser()
group1 = parser.add_argument_group('group1') # can take description as well
group1.add_argument('-a', '--aa',
help = "option a",
dest = 'a',
action = 'store',
)
group1.add_argument('-b', '--bb',
help = "option b",
dest = 'b',
action = 'store',
)
group2 = parser.add_argument_group('group 2')
group2.add_argument('-c', '--cc',
help = "option c",
dest = 'c',
action = 'store',
)
group2.add_argument('-d', '--dd',
help = "option d",
dest = 'd',
action = 'store',
)