开发者

Python optparse not working for me

开发者 https://www.devze.com 2022-12-27 12:30 出处:网络
I\'m currently learning on how to use the Python optparse module. I\'m trying the following example script but the args variable comes out empty. I tried this using Python 2.5 and 2.6 but to no avail.

I'm currently learning on how to use the Python optparse module. I'm trying the following example script but the args variable comes out empty. I tried this using Python 2.5 and 2.6 but to no avail.

import optparse

def main():
  p = optparse.OptionParser()
  p.add_option('--person', '-p', action='store', dest='person', default='Me')
  options, args = p.parse_a开发者_如何学JAVArgs()

  print '\n[Debug]: Print options:', options
  print '\n[Debug]: Print args:', args
  print

  if len(args) != 1:
    p.print_help()
  else:
    print 'Hello %s' % options.person

if __name__ == '__main__':
  main() 

Output:

>C:\Scripts\example>hello.py -p Kelvin

[Debug]: Print options: {'person': 'Kelvin'}

[Debug]: Print args: []

Usage: hello.py [options]

Options: -h, --help show this help message and exit -p PERSON, --person=PERSON


The args variable holds any arguments that were not assigned to an option. Your code is indeed working properly by assigning Kelvin to the person option variable.

If you tried running hello.py -p Kelvin file1.txt, you would find that person still was assigned the value "Kelvin", and then your args would contain "file1.txt".

See also the documentation on optparse:

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


According to optparse help:

"On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options."

Try hello.py -p Kelving abcd - 'Kelvin' will be parsed by optparse, 'abcd' will land in args variable returned by parse_args


Note: "options" is a dictionary with the options you added. "Args" is a list with the unparsed arguments. You should not be looking at length "args". Here is a transcript to illustrate:

moshez-mb:profile administrator$ cat foo
import optparse

def main():
    p = optparse.OptionParser()
    p.add_option('--person', '-p', action='store', dest='person', default='Me')
    options, args = p.parse_args()
    print '\n[Debug]: Print options:', options
    print '\n[Debug]: Print args:', args
    print
    if len(args) != 1:
        p.print_help()
    else:
        print 'Hello %s' % options.person

if __name__ == '__main__':
    main()
moshez-mb:profile administrator$ python foo

[Debug]: Print options: {'person': 'Me'}

[Debug]: Print args: []

Usage: foo [options]

Options:
  -h, --help            show this help message and exit
  -p PERSON, --person=PERSON
moshez-mb:profile administrator$ python foo -p Moshe

[Debug]: Print options: {'person': 'Moshe'}

[Debug]: Print args: []

Usage: foo [options]

Options:
  -h, --help            show this help message and exit
  -p PERSON, --person=PERSON
moshez-mb:profile administrator$ python foo -p Moshe argument

[Debug]: Print options: {'person': 'Moshe'}

[Debug]: Print args: ['argument']

Hello Moshe
moshez-mb:profile administrator$ 


import ast

(options, args) = parser.parse_args()
noargs = ast.literal_eval(options.__str__()).keys()
if len(noargs) != 1:
    parser.error("ERROR: INCORRECT NUMBER OF ARGUMENTS")
    sys.exit(1)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号