遵循命令时,双破折号做什么? [英] What does double-dash do when following a command?

查看:156
本文介绍了遵循命令时,双破折号做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

双破折号后出现命令时,应用程序应如何解析命令行? (未复制)

How a app should parse command line when there is a Command after a double dash? (Not duplicated of this and this)

我知道双破折号通常会做什么:

I know what will double dash normally do:

A-表示选项结束并禁用其他选项 加工. -之后的所有参数均视为文件- 名称和参数. -的参数等效于-

A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as file‐ names and arguments. An argument of - is equivalent to --

因此,它将以下内容设置为参数,例如: myapp -f <args> ...然后$ myapp -f -- -a -b会将-a-b视为-f的参数,而不是Flags

So it set the following things as arguments, for example: myapp -f <args> ... Then $ myapp -f -- -a -b will treat -a and -b as arguments of -f, instead of Flags

但是当需要一个应用程序时会发生什么:

But what will happen when an app required:

myapp cmd <arg> -f <args>...

并且命令行为$ myapp -f -- test cmd sth,应将其解析为:

And the command line is $ myapp -f -- test cmd sth, Should it parsed as:

  • myapp收到带有参数testcmdsth
  • -f标志
  • myapp收到了cmd命令,后跟sth,是带有参数test
  • -f
  • myapp received a -f Flag with arguments test, cmd and sth
  • or myapp received a cmd Command followed by sth, a -f with argument test

我正在为python编写命令行解析器,所以我需要知道它的行为.

I'm writing a command line parser for python so I need to know how it should behave.

非常感谢:)

推荐答案

您写过

$ myapp -f -- -a -b会将-a和-b视为-f的参数,而不是Flags

$ myapp -f -- -a -b will treat -a and -b as arguments of -f, instead of Flags

不完全是.双破折号使-a-b自变量成为myapp.如果-f需要一个参数,则使用双破折号会出现错误,因为没有给出这样的参数.

Not quite. The double dash makes -a and -b arguments to myapp. If -f is expecting an argument, using a double dash there will raise an error, since no such argument is given.

如果您的解析器定义了子解析器,则位于其前面的所有选项均假定为由主解析器定义的选项,并且子命令后的所有选项均属于子解析器.例如,使用

If your parser defines a sub parser, any options that precede it are assumed to be options defined by the main parser, and any options the follow the subcommand are part of the sub parser. For example, with

p = ArgumentParser()
p.add_argument("-v", action='store_true')
sp = p.add_subparsers()
p1 = sp.add_parser('cmd')
p1.add_argument('-v')

命令行myapp -v cmd -v test将对两个-v进行不同的处理;第一个是在p上定义的store_true选项,第二个是在p1上定义的选项.您的命令行

the command line myapp -v cmd -v test would treat the two -v differently; the first is the store_true option defined on p, the second the option defined on p1. Your command line

myapp -f -- test cmd sth

如果-f需要一个参数,则

会产生错误.如果-f不是,则myapp只是一个选项-f和3个位置参数testcmdsth.

produces an error if -f expects an argument. If -f does not, then myapp simply one option -f and 3 positional arguments test, cmd, and sth.

这篇关于遵循命令时,双破折号做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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