不要在最后一个位置参数之后解析选项 [英] Don't parse options after the last positional argument

查看:26
本文介绍了不要在最后一个位置参数之后解析选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 ssh 命令行客户端编写一个包装器.在 command 的第一个位置参数之后,所有其他选项也应视为位置参数.

I'm writing a wrapper around the ssh command line client. After the first positional argument that's part of command, all further options should also be treated as positional arguments.

optparse 下,我相信这可以通过 disable_interspersed_args.

Under optparse, I believe this would be done with disable_interspersed_args.

目前我有这样的事情:

parser = argparse.ArgumentParser()
parser.add_argument('--parallel', default=False, action='store_true')
# maybe allow no command? this would ssh interactively into each machine...
parser.add_argument('command', nargs='+')
args = parser.parse_args()

但如果选项作为命令的一部分传递(例如 my_wrapper ls -l),它们会被 ArgumentParser 解释为未知选项.错误:无法识别的参数:-l

But if options are passed as part of the command (such as my_wrapper ls -l), they're instead interpreted by ArgumentParser as unknown options. error: unrecognized arguments: -l

如果我使用 parse_known_args(), 选项可能会乱序.

If I use parse_known_args(), the options may be taken out of order.

p = argparse.ArgumentParser()
p.add_argument('-a', action='store_true')
p.add_argument('command', nargs='+')
print(p.parse_known_args())

$ python3 bah.py -b ls -l -a
(Namespace(a=True, command=['ls']), ['-b', '-l'])

这里可以看到ls之前-b的位置已经丢失了,-a已经从命令中解析出来了,这是不想要的.

Here you can see that -b's position before ls has been lost, and -a has been parsed out from the command, which is not desired.

我该怎么做:

  • 防止参数在某个点之后被解析?
  • 禁用散布参数的解析?
  • 允许带前缀的参数作为位置参数使用吗?

推荐答案

我遇到了同样的问题.我在 argparse 错误跟踪器上找到了解决方案:http://code.google.com/p/argparse/issues/detail?id=52

I had the same problem. I found the solution on the argparse bug tracker: http://code.google.com/p/argparse/issues/detail?id=52

解决方案很简单:将 nargs='+'(或 '*')替换为 nargs=argparse.REMAINDER.这个特殊值没有记录在案,但它可以满足您的需求.

The solution is simple: replace nargs='+' (or '*') with nargs=argparse.REMAINDER. This special value is not documented, but it does what you want.

这篇关于不要在最后一个位置参数之后解析选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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