How to give an error when no options are given with optparse
Posted
by Acorn
on Stack Overflow
See other posts from Stack Overflow
or by Acorn
Published on 2010-04-16T04:30:26Z
Indexed on
2010/04/16
4:33 UTC
Read the original article
Hit count: 337
python
I'm try to work out how to use optparse, but I've come to a problem.
My script (represented by this simplified example) takes a file, and does different things to it depending on options that are parsed to it. If no options are parsed nothing is done.
It makes sense to me that because of this, an error should be given if no options are given by the user. I can't work out how to do this.
Am I using options in the wrong way? If so, how should I be doing it instead?
#!/usr/bin/python
from optparse import OptionParser
dict = {'name': foo, 'age': bar}
parser = OptionParser()
parser.add_option("-n", "--name", dest="name")
parser.add_option("-a", "--age", dest="age")
(options, args) = parser.parse_args()
if options.name:
dict['name'] = options.name
if options.age:
dict['age'] = options.age
print dict
#END
© Stack Overflow or respective owner