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

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

问题描述

我正在围绕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解释为未知选项. error: unrecognized arguments: -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天全站免登陆