18

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.

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

Presently I have something like this:

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()

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

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'])

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.

How can I:

  • Prevent arguments from being parsed after a certain point?
  • Disable parsing of interspersed arguments?
  • Allow arguments with a prefix to be consumed as positional arguments?
4

3 回答 3

19

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

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

于 2011-07-12T21:33:43.340 回答
5

I think your best bet to start solving these issues is to try out -- after all your optional args. -- is a pseudo-arg that tells ArgumentParser that everything after is a positional argument. Docs are here

As for prevent arguments from being parsed after a certain point, you can pass part of argv to parse_args. That combined with some introspection can be used to limit what is parsed.

于 2011-06-27T05:37:10.753 回答
-1

另一种选择是使用parse_known_args,它会在遇到未知参数时停止解析。

于 2014-08-05T13:27:22.367 回答