467,222 Members | 1,402 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,222 developers. It's quick & easy.

optparse: Why does this syntax work and not another?

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?
Jul 18 '05 #1
  • viewed: 2823
Share:
3 Replies
washu wrote:
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
Jul 18 '05 #2
On Mon, 05 Jul 2004 06:36:46 GMT, washu <me@privacy.net> wrote:
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.

Jul 18 '05 #3
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.
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Hans-Joachim Widmaier | last post: by
7 posts views Thread by Henry Ludemann | last post: by
1 post views Thread by sector119 | last post: by
3 posts views Thread by Bob | last post: by
3 posts views Thread by Dan | last post: by
2 posts views Thread by Tim Arnold | last post: by
reply views Thread by Robert Kern | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.