遵循命令时,双破折号做什么? [英] What does double-dash do when following a command?
问题描述
问题:
双破折号后出现命令时,应用程序应如何解析命令行? (未复制此和此)
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
收到带有参数test
,cmd
和sth
的 - 或
myapp
收到了cmd
命令,后跟sth
,是带有参数test
的
-f
标志
-f
myapp
received a-f
Flag with argumentstest
,cmd
andsth
- or
myapp
received acmd
Command followed bysth
, a-f
with argumenttest
我正在为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个位置参数test
,cmd
和sth
.
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屋!