getopt not raising exception

Matt Nordhoff mnordhoff at
Sun Jan 10 12:57:43 CET 2010

Matthew Lear wrote:
> Hello,
> I'm having problems getting getopt to function correctly. Basically, no
> exception is being raised if no argument is passed to the code snippet
> below. I've read the Python documentation and tried example code from
> various sources which should cause an exception, only they don't. I've
> also tried executing the code on different machines too but to no avail.
> I'm sure I'm obviously doing something wrong but can't determine what.
> Any help would be much appreciated indeed.
> import sys, getopt
> try:
>         opts, args = getopt.getopt(sys.argv, "h:", ["help"])
> except getopt.GetoptError:
>         print "error"
>         sys.exit(2)
> If no args are passed when the script is run there is no exception
> raised. Why? Surely the "h:" means that this option must be passed?
> Thanks,
> --  Matt

That's not what ":" means. It means that, *if* the option is passed, it
must be followed by an additional argument, e.g.: -h something

If you require that -h be passed, it's not much of an option! You should
use a regular argument and check len(args) or somesuch. Or, if you must
keep it an "option", do something equivalent for that.

BTW: Checked out optparse? It's bigger and sexier!
Matt Nordhoff

More information about the Python-list mailing list