Python optparse not working for me

I am currently learning how to use the Ppton optparse module. I try the following example script, but the args variable comes out empty. I tried this with 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_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() 

Conclusion:

>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

+3
source share
4 answers

The variable argscontains any arguments that were not assigned to the parameter. Your code really works correctly by assigning to a Kelvinvariable person.

hello.py -p Kelvin file1.txt, , person "Kelvin", args "file1.txt".

. optparse:

parse_args() :

  • options, , . --file , options.file , , None,
  • args,
+6

. "" - . "Args" - . "args". , :

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

According to optparsehelp:

"On success, a pair is returned (values, args), where" values ​​"is an instance of Values ​​(with all your parameter values), and" args "is the list of arguments to the left after parsing the parameters."

Try it hello.py -p Kelving abcd- "Kelvin" will be analyzed by optparse, "abcd" will land in the variable argsreturnedparse_args

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

Source: https://habr.com/ru/post/1742131/


All Articles