質問

I saw this page: http://docs.python.org/2/library/optparse.html

wrote this code:

parser = optparse.OptionParser(usage=use)
parser.add_option("-z", dest="zipname")
parser.add_option("-d", dest="dictionary")

(options, args) = parser.parse_args()
print len(args)

so I tried it with:

script.py -z hello.zip -d world.txt

and got:

>> 0

when I use options.zipname or options.dictionary it's alright but nothing goes into args, why? thanks.

役に立ちましたか?

解決

The args return value of parse_args is the "the leftover positional arguments after all options have been processed" (http://docs.python.org/2/library/optparse.html#parsing-arguments). It parsed all the arguments you gave it, so there is nothing left to put in args.

If you run, for example,

script.py -z hello.zip -d world.txt foo bar

then 2 will be printed.

P.S. As @Michael0x2a pointed out in a comment, the optparse library is deprecated. Take a look at the argparse library.

他のヒント

Because args are the leftover args after processing. From the docs:

parse_args() returns two values:

  • options, an object containing values for all of your options—e.g. if --file takes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option
  • args, the list of positional arguments leftover after parsing options
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top