[Tutor] getopt question

Michael Janssen Janssen at rz.uni-frankfurt.de
Tue Jan 20 08:22:44 EST 2004


On Wed, 21 Jan 2004, Xuer wrote:

> an example from 'Python Programming for Beginners'
>
> trygetopt.py
> -----------------------------------------------------------------
> #!/usr/bin/python
>
> import sys,getopt
> try:
>         options, xarguments = getopt.getopt(sys.argv[1:],'ha')
> except getopt.error:
>         pass
>
> print options
> ------------------------------------------------------------------
>
> ./trygetopt.py -ha
> get result
> [('-h', ''), ('-a', '')]
>
> but ./trygetopt.py -h 123 -a 456
> get the result
> [('-h', '')]
>
> While I expect the result would be
> [('-h', '123'), ('-a', '456')]
>
> what's the matter?
> thanks in advance. :)

when you want to have a option with a parameter, then you have to
instruct getopt so. getopt.getopt(sys.argv[1:],'h:a:') is the syntax for
this (A colon behind any option that needs a parameter).  It might
be that you then *have* to specify a parameter on commandline.

Why not using optparse? It's newer and worth the change (ease of use,
automatic help output). Consult the Library Reference for this.


Michael




More information about the Tutor mailing list