getopt

John Machin sjmachin at lexicon.net
Wed Feb 11 00:54:25 EST 2009


On Feb 11, 12:25 pm, John Machin <sjmac... at lexicon.net> wrote:
> On Feb 11, 12:12 pm, Matthew Sacks <ntw... at gmail.com> wrote:
>
> > if anyone can have a look at this code and offer suggestions i would
> > appreciate it.
> > i am forced to use getopt, so i cant use something good like optparse
>
> > passedArgs = sys.argv[1:]
> > optlist, args = getopt.getopt(str(passedArgs), ["connectPassword=",
>
> Dunno where you acquired the str() ... just lose it. Consider checking
> with the documentation when something "does not work".

Rule 2: read further in the documentation than you think you need
to :-)

You have omitted the second arg, the one that defines short options.
As for the second part of your question, assigning to locals is
tedious as you have found. The classical solution is to jam the
options into an object that acts like a 'record' or a 'struct'.
Another possibility is the newfangled 'named tuple'. The following
illustrates working code for getting your optlist going, and using the
'record' idea. Keep on going (next step: add a function for each arg
that will convert the value from str to int/float/bool/etc as/if
appropriate) and you will have rewritten optparse.

HTH,
John

================
C:\junk>type getopt_demo.py
import getopt, sys
long_arg_defns = { # sets up defaults
    "cp":  None,
    "asu": "xyzzy",
    "act": "do_nothing",
    "tgts":"",
    "ad": 1.23,
}
long_arg_list = [x + '=' for x in long_arg_defns.keys()]
passedArgs = sys.argv[1:]
print 'passedArgs', passedArgs

print '\nattempt 1'
try:
    optlist, args = getopt.getopt(str(passedArgs), long_arg_list)
    print optlist, args
except Exception, e:
    print "%s: %s" % (e.__class__.__name__, e)

print '\nattempt 2'
try:
    optlist, args = getopt.getopt(passedArgs, long_arg_list)
    print optlist, args
except Exception, e:
    print "%s: %s" % (e.__class__.__name__, e)

print '\nattempt 3'
try:
    optlist, args = getopt.getopt(passedArgs, '', long_arg_list)
    print optlist, args
except Exception, e:
    print "%s: %s" % (e.__class__.__name__, e)

class Record(object):

    def __init__(self, initial_dict, optlist):
        for attr, default in initial_dict.items():
            setattr(self, attr, default)
        for attr, value in optlist:
            setattr(self, attr.lstrip('-'), value)

    def __str__(self):
        return "<Record: %s>" % self.__dict__

r = Record(long_arg_defns, optlist)
print
print r
print
print r.cp, r.act, r.ad


C:\junk>getopt_demo.py --cp xxxcp --ad yyyyyad extra1 extra2
passedArgs ['--cp', 'xxxcp', '--ad', 'yyyyyad', 'extra1', 'extra2']

attempt 1
[] ['--cp', 'xxxcp', '--ad', 'yyyyyad', 'extra1', 'extra2']

attempt 2
GetoptError: option --cp not recognized

attempt 3
[('--cp', 'xxxcp'), ('--ad', 'yyyyyad')] ['extra1', 'extra2']

<Record: {'tgts': '', 'cp': 'xxxcp', 'ad': 'yyyyyad', 'asu': 'xyzzy',
'act': 'do _nothing'}>

xxxcp do_nothing yyyyyad

C:\junk>



More information about the Python-list mailing list