[Tutor] getopt question

Michael P. Reilly arcege@shore.net
Thu, 27 Jul 2000 18:53:07 -0400 (EDT)


> 
> 
> Hi, I'm having some confusion with the getopt module. Is there a better
> way to do this? 
> 
> --
> 
> #!/usr/local/bin/python
> 
> import getopt
> import sys
> 
> try:
>     options, argument = getopt.getopt(sys.argv[1:], 'hbt')
> except getopt.error:
>     print "getopt.error - sorry."
>     sys.exit(0)
> 
> for i in range(len(options)):
>     if '-h' in options[i]:
>         print "You need help"
>     if '-b' in options[i]:
>         print "You need bash"
>     if '-t' in options[i]:
>         print "You need tcsh"

I would usually write:

try:
  opts, args = getopt.getopt(sys.argv[1:], 'bhts:')
except getopt.error, value:
  raise SystemExit('%s: %s' % (sys.argv[0], value))

for (opt, val) in opts:
  if opt == '--':
    break
  elif opt == '-h':
    print 'you need help'
  elif opt == '-b':
    print 'you need bash'
  elif opt == '-t':
    print 'you need tcsh (yeah, right)'
  elif opt == '-s':
    print 'you need', val

You could use a dict instead of the if-elif-elif, but that's just
style.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------