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_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()
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
argsvariable holds any arguments that were not assigned to an option. Your code is indeed working properly by assigningKelvinto thepersonoption variable.If you tried running
hello.py -p Kelvin file1.txt, you would find thatpersonstill was assigned the value"Kelvin", and then yourargswould contain"file1.txt".See also the documentation on
optparse: