optparse: Why does this syntax work and not another?

W

washu

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?
 
P

Peter Otten

washu said:
optparse.OptionParser().add_option( . . .)
Here you create an OptionParser instance and add one options
(options, args) = optparse.OptionParser().parse_args( . . . )

Here you create a NEW OptionParser instance with no options and feed the
arguments to it.

Peter
 
A

Anthony Baxter

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"

Because your code is incorrect. The first of these two lines
creates and OptionParser() instance, and calls 'add_option()'
on it. It then throws away the newly created instance, as you
didn't assign it to anything.
 
W

washu

Thanks Anthony and Peter,

I didn't realize that optparse.OptionParser() was a class. It makes sense
now. Now that I think about it, it's obvious that it has to be a class.
Luckily, it gave me an excuse to down a couple of Guinness's.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Optparse to parsing Suggestions !! 0
Python : parsing the command line options using optparse 0
optparse options 2
optparse 3
optparse eats $ 2
optparse TypeError 5
optparse 4
Removing option from optparse 1

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top