[英]How to create subparser with argparse from existing program in Python 3?
If one has an executable mini_program.py
that uses argparse
with the following structure: 如果有一个可执行文件mini_program.py
,它使用具有以下结构的argparse
:
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-X', '--attribute_matrix', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
parser.add_argument('-y', '--target_vector', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
opts = parser.parse_args()
if __name__ == "__main__":
main()
How can one create a controller program parent_program.py
that uses argparse
(I think with subparser
?) to have a similar usage to below: 如何创建一个控制器程序parent_program.py
,该程序使用argparse
(我认为与subparser
?)具有与以下类似的用法:
python parent_program.py --help
blah-blah list of programs that can be used
then using the subprogram: 然后使用子程序:
python parent_program.py mini_program --help
-X description
-y description
etc...
How could all of the parameters propagate up from mini_program.py
to the parent_program.py
? 所有参数如何从mini_program.py
传播到parent_program.py
?
import argparse
def main():
parser = argparse.ArgumentParser()
# Subprograms
subprograms = parser.add_subparsers(title="subprograms")
# ============
# mini-program
# ============
parser_miniprogram = subprograms.add_parser("miniprogram")
# Input
parser_miniprogram.add_argument('-X', '--attribute_matrix', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
parser_miniprogram.add_argument('-y', '--target_vector', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
opts = parser.parse_args()
opts_miniprogram = parser_miniprogram.parse_args()
print(opts_miniprogram.__dict__)
if __name__ == "__main__":
main()
# parent program
python parent_program.py --help
usage: parent_program.py [-h] {miniprogram} ...
optional arguments:
-h, --help show this help message and exit
subprograms:
{miniprogram}
# miniprogram
python parent_program.py miniprogram --help
usage: parent_program.py miniprogram [-h] [-X ATTRIBUTE_MATRIX]
[-y TARGET_VECTOR]
optional arguments:
-h, --help show this help message and exit
-X ATTRIBUTE_MATRIX, --attribute_matrix ATTRIBUTE_MATRIX
Input: Path/to/Tab-separated-value.tsv
-y TARGET_VECTOR, --target_vector TARGET_VECTOR
Input: Path/to/Tab-separated-value.tsv
python parent_program.py miniprogram -X ../../Data/X_iris.noise_100.tsv.gz -y ../../Data/y_iris.tsv
usage: parent_program.py miniprogram [-h] [-X ATTRIBUTE_MATRIX]
[-y TARGET_VECTOR]
parent_program.py miniprogram: error: unrecognized arguments: miniprogram
The parent program could have code like 父程序可能具有如下代码
import mini_program
import sys
<do its own parsing>
if 'use_mini':
<modify sys.argv>
mini_program.main()
As written, importing mini_program
doesn't run its parser. 按照书面规定,导入mini_program
不会运行其解析器。 But calling its main
will, but using the list it finds in sys.argv
. 但是调用它的main
意愿,但是使用它在sys.argv
找到的列表。
The parent parser should be written in a way that it accepts arguments that it needs, and doesn't choke on inputs the mini
wants, '-X' and '-y'. 父解析器的编写方式应使其接受所需的参数,并且不要阻塞mini
想要的输入“ -X”和“ -y”。 It would then puts those 'extra' values in a modified sys.argv
, which the mini
parser can handle. 然后,将这些“额外”值放入经过修改的sys.argv
, mini
解析器可以处理。
parse_known_args
is one way of accepting unknown arguments, https://docs.python.org/3/library/argparse.html#partial-parsing parse_known_args
是接受未知参数的一种方法, https: parse_known_args
nargs=argparse.REMAINDER
, https://docs.python.org/3/library/argparse.html#nargs , is another way of collecting remaining arguments for passing on. nargs=argparse.REMAINDER
, https: nargs=argparse.REMAINDER
,是另一种收集剩余参数以进行传递的方法。
If mini
main
was written as: 如果mini
main
编写为:
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('-X', '--attribute_matrix', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
parser.add_argument('-y', '--target_vector', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
opts = parser.parse_args(argv)
it could be called with 可以用
mini_program.main(['-X', 'astring','-y','another'])
that is, with an explicit argv
list, instead of working through sys.argv
. 也就是说,使用显式的argv
列表,而不是通过sys.argv
进行工作。
Keeping the main parser from responding to a '-h' help could be tricky. 阻止主解析器响应“ -h”帮助可能很棘手。 subparsers
is probably the cleanest way of doing that. subparsers
可能是最干净的方法。
You could combine subparsers with the invocation of a the mini
main
. 您可以将子解析器与mini
main
的调用结合使用。 I won't try to work out those details now. 我现在不会尝试得出这些细节。
Another way to define the main
is: 定义main
另一种方法是:
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-X', '--attribute_matrix', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
parser.add_argument('-y', '--target_vector', type=str, help = 'Input: Path/to/Tab-separated-value.tsv')
return parser
And use it as 并用作
opts = main().parse_args()
opts = mini_program.main().parse_args()
in other words, use main
to define the parser, but delay the parsing. 换句话说,使用main
来定义解析器,但是会延迟解析。
My actual solution was an adaptation to the above: 我的实际解决方案是对以上内容的适应:
# Controller
def main(argv=None):
parser = argparse.ArgumentParser(prog="parent_program", add_help=True)
parser.add_argument("subprogram")
opts = parser.parse_args(argv)
return opts.subprogram
# Initialize
if __name__ == "__main__":
# Get the subprogram
subprogram = main([sys.argv[1]])
module = importlib.import_module(subprogram)
module.main(sys.argv[2:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.