getopt

M

Matthew Sacks

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=",
"adminServerURL=", "action=", "targets=", "appDir="])


for some reason this does not work in assigning args to opts.


i want to take all of the command line options and assign them to strings

here is how i am currently going about it

for o,a in optlist:
if o == "--connectPassword":
connectPassword = a
print "Connect password assigned as " + a
continue
elif o == "--adminServerURL":
adminServerURL = a
print "adminServerURL " + a
continue
else:
print "No connection Arguments Specified"


TIV
 
J

John Machin

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".
"adminServerURL=", "action=", "targets=", "appDir="])

for some reason this does not work in assigning args to opts.
 
M

Matthew Sacks

The documentation leaves lack for want, especially the examples.

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".
"adminServerURL=", "action=", "targets=", "appDir="])

for some reason this does not work in assigning args to opts.
 
J

John Machin

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>
 
J

John Machin

The documentation leaves lack for want, especially the examples.

You had two problems:

(1) str(passedArgs): The docs make it plain that "args" is a list, not
a str instance: """args is the argument list to be parsed, without the
leading reference to the running program. Typically, this means
sys.argv[1:]""". The 1st and 2nd examples spell out the same story;
here's the 2nd:
"""
Using long option names is equally easy: ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x',
'a1', 'a2']
"""

(2) omitting the *required* options arg: (a) it's not wrapped in [] so
it's required (b) the docs say """To accept only long options, options
should be an empty string."""

IOW, it may "leave lack for want", but not in the areas causing you a
bother.
 
M

Matthew Sacks

I didn't realize that the no-value arguments, -b, -h, etc are required?
This seems to make things a bit more difficult considering unless I
use the GNU style getopt all arguments are required to be passed?

I could be mistaken.

I will have a look at what you have posted here and report my results.
I appreciate the response.

M

The documentation leaves lack for want, especially the examples.

You had two problems:

(1) str(passedArgs): The docs make it plain that "args" is a list, not
a str instance: """args is the argument list to be parsed, without the
leading reference to the running program. Typically, this means
sys.argv[1:]""". The 1st and 2nd examples spell out the same story;
here's the 2nd:
"""
Using long option names is equally easy:['--condition=foo', '--testing', '--output-file', 'abc.def', '-x',
'a1', 'a2']
"""

(2) omitting the *required* options arg: (a) it's not wrapped in [] so
it's required (b) the docs say """To accept only long options, options
should be an empty string."""

IOW, it may "leave lack for want", but not in the areas causing you a
bother.
 
J

John Machin

I didn't realize that the no-value arguments, -b, -h, etc are required?

required sense 1: the 2nd arg of the function is required; if there
are to be no short options, the 2nd arg should be an empty string.

required sense 2: you are required to specify *all* short options that
you will accept, whether they are no-value or value options; otherwise
you would have to do your own checking for unacceptable options
This seems to make things a bit more difficult considering unless I
use the GNU style getopt all arguments are required to be passed?

What does "all arguments are required to be passed" mean? The user is
not required to supply an arg corresponding to any option. Options are
optional!

GNU? Change getopt.getopt to getopt.gnu_getopt and you still get an
exception like "GetoptError: option -b not recognized" if -b is not
defined in the 2nd arg of [gnu_]getopt. AFAICT the GNU difference is
only the documented different treatment of an arg string like "-a1 -b
bvalue stray -c -d" ... non-Gnu treats -c and -d the same as stray.
I will have a look at what you have posted here and report my results.

Just bear in mind that it was written under the assumption that you
weren't plannning to use short options at all; your examples left lack
for want.

Cheers,
John
 

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

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top