How to generate error when argument are not supplied and there is no explicit defults (in optparse)?

Peng Yu pengyu.ut at gmail.com
Fri Oct 14 17:29:50 EDT 2011


Hi,

The following code doesn't give me error, even I don't specify the
value of filename from the command line arguments. filename gets
'None'. I checked the manual, but I don't see a way to let
OptionParser fail if an argument's value (which has no default
explicitly specified) is not specified. I may miss some thing in the
manual. Could any expert let me know if there is a way to do so?
Thanks!

#!/usr/bin/env python

from optparse import OptionParser

usage = 'usage: %prog [options] arg1 arg2'
parser = OptionParser(usage=usage)
parser.set_defaults(verbose=True)
parser.add_option('-f', '--filename')

#(options, args) = parser.parse_args(['-f', 'file.txt'])
(options, args) = parser.parse_args()

print options.filename



-- 
Regards,
Peng



More information about the Python-list mailing list