getopt, i don't get it

D

Dominik Kaspar

I tried to use getopt and copied the example from:
http://www.python.org/doc/current/lib/module-getopt.html

but nothing is working... getopt.GetoptError doesn't seem to exist and
when i run the program commenting this out, none of "-v", "-h" and
"-o" wants to be recognized... what's the matter?!

Dominik


import getopt, sys

def usage():
print "Use it like this: bla bla bla"

def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help",
"output="])
except: # getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-o", "--output"):
output = a
# ...

if __name__ == "__main__":
main()
 
P

Peter Hansen

Dominik said:
I tried to use getopt and copied the example from:
http://www.python.org/doc/current/lib/module-getopt.html

but nothing is working... getopt.GetoptError doesn't seem to exist and
when i run the program commenting this out, none of "-v", "-h" and
"-o" wants to be recognized... what's the matter?!

It seems likely you have another file called getopt.py (or perhaps
a leftover getopt.pyc from a previous time) in your Python path
(check all directories in sys.path, starting with current directory).

You can't safely reuse the names of standard library modules most
of the time...

-Peter
 
J

Josef Meile

If you haven't used getopt before, don't start now. Check out optparse
Thanks for the tip, I have already wrote something with getopt, but I found
that the "add_option" of the optparse is cleaner and easier to read than the
list of options that you use with getopt. Other thing I liked is that you
don't
have to write a method to print the help, you just pass a descriptive text
to the parser and it will do the rest.

Really nice :). I will try it.

Regards,
Josef
 

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

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top