使用 argparse 保持参数不变
我想使用 argparse 来解析它知道的参数,然后保留其余部分不变。例如,我希望能够运行
performance -o output other_script.py -a opt1 -b opt2
Which 使用 -o
选项,而其余部分保持不变。
模块 profiler.py 与 optparse 做了类似的事情,但由于我使用的是 argparse 我正在做:
def parse_arguments():
parser = new_argument_parser('show the performance of the given run script')
parser.add_argument('-o', '--output', default='profiled.prof')
return parser.parse_known_args()
def main():
progname = sys.argv[1]
ns, other_args = parse_arguments()
sys.argv[:] = other_args
这似乎也有效,但如果 other_script.py 也有一个 -o
会发生什么旗帜?
一般来说有更好的方法来解决这个问题吗?
I would like use argparse to parse the arguments that it knows and then leave the rest untouched. For example I want to be able to run
performance -o output other_script.py -a opt1 -b opt2
Which uses the -o
option and leaves the rest untouched.
The module profiler.py does a similar thing with optparse, but since I'm using argparse I'm doing:
def parse_arguments():
parser = new_argument_parser('show the performance of the given run script')
parser.add_argument('-o', '--output', default='profiled.prof')
return parser.parse_known_args()
def main():
progname = sys.argv[1]
ns, other_args = parse_arguments()
sys.argv[:] = other_args
Which also seems to work, but what happens if also other_script.py also has a -o
flag?
Is there in general a better way to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以使用 nargs=argparse.REMAINDER 向解析器添加位置参数,以捕获脚本及其选项:
运行上述最小脚本...
You could also add a positional argument to your parser with
nargs=argparse.REMAINDER
, to capture the script and its options:Running the above minimal script...
argparse
将停止解析参数,直到 EOF 或--
。如果你想有参数而不被 argparse 解析,你可以写::argparse
will stop to parse argument until EOF or--
. If you want to have argument without beeing parsed by argparse, you can write::