Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

linux - What does double-dash do when following a command?

Question:

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

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>...

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

  • 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

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

Thx a lot :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You wrote

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

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...