optparse: Why does this syntax work and not another?

washu me at privacy.net
Mon Jul 5 02:36:46 EDT 2004


Hi,

I'm was going through the module help located on
http://docs.python.org/lib/optparse-store-action.html and I tried
modifying it a tiny bit and things don't work.  If someone could tell me
what I'm doing wrong, I'd appreciate it.

The script that works (based on the code on the webpage) is:
#!/usr/bin/env python

import optparse, sys

parser = optparse.OptionParser()

parser.add_option("-f", action="store", type="string", dest="file_name")
(options, args) = parser.parse_args(sys.argv[1:])
print(options.file_name)

I call the script (optparse_test.py) in this fashion:
./optparse_test.py -f foo.txt

And everything works.  It will print foo.txt.  Now, instead of doing the
parser = optparse.OptionParser() substitution, I spell everything out:

optparse.OptionParser().add_option( . . .)
(options, args) = optparse.OptionParser().parse_args( . . . )

And the script stops with an error message of: "no such option: -f"

Anyone know why one syntax works and why the other doesn't?



More information about the Python-list mailing list