Search code examples
pythonargsoptparse

optparse args gets nothing (python)


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.


Solution

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