获取 argparse 中的剩余参数 [英] Getting the remaining arguments in argparse

查看:32
本文介绍了获取 argparse 中的剩余参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一次获得所有剩余的未使用参数.我该怎么做?

parser.add_argument('-i', action='store', dest='i', default='i.log')parser.add_argument('-o', action='store', dest='o', default='o.log')

解决方案

另一种选择是向解析器添加位置参数.指定不带前导破折号的选项,当没有其他选项被识别时 argparse 将查找它们.这具有改进命令的帮助文本的额外好处:

<预><代码>>>>parser.add_argument('otherthings', nargs='*')>>>parser.parse_args(['foo', 'bar', 'baz'])命名空间(i='i.log', o='o.log', otherthings=['foo', 'bar', 'baz'])

<预><代码>>>>打印 parser.format_help()用法:ipython-script.py [-h] [-i I] [-o O] [otherthings [otherthings ...]]位置参数:其他事情可选参数:-h, --help 显示此帮助信息并退出-i 我-o O

I want to get all the remaining unused arguments at once. How do I do it?

parser.add_argument('-i', action='store', dest='i', default='i.log')
parser.add_argument('-o', action='store', dest='o', default='o.log')

解决方案

Another option is to add a positional argument to your parser. Specify the option without leading dashes, and argparse will look for them when no other option is recognized. This has the added benefit of improving the help text for the command:

>>> parser.add_argument('otherthings', nargs='*')
>>> parser.parse_args(['foo', 'bar', 'baz'])
Namespace(i='i.log', o='o.log', otherthings=['foo', 'bar', 'baz'])

and

>>> print parser.format_help()
usage: ipython-script.py [-h] [-i I] [-o O] [otherthings [otherthings ...]]

positional arguments:
  otherthings

optional arguments:
  -h, --help   show this help message and exit
  -i I
  -o O

这篇关于获取 argparse 中的剩余参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆