getopt

Discussion in 'Python' started by Matthew Sacks, Feb 11, 2009.

  1. 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
    Matthew Sacks, Feb 11, 2009
    #1
    1. Advertising

  2. Matthew Sacks

    John Machin Guest

    On Feb 11, 12:12 pm, Matthew Sacks <> 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".

    > "adminServerURL=", "action=", "targets=", "appDir="])
    >
    > for some reason this does not work in assigning args to opts.
    >
    John Machin, Feb 11, 2009
    #2
    1. Advertising

  3. The documentation leaves lack for want, especially the examples.

    On Tue, Feb 10, 2009 at 5:25 PM, John Machin <> wrote:
    > On Feb 11, 12:12 pm, Matthew Sacks <> 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".
    >
    >> "adminServerURL=", "action=", "targets=", "appDir="])
    >>
    >> for some reason this does not work in assigning args to opts.
    >>

    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    Matthew Sacks, Feb 11, 2009
    #3
  4. Matthew Sacks

    John Machin Guest

    On Feb 11, 12:25 pm, John Machin <> wrote:
    > On Feb 11, 12:12 pm, Matthew Sacks <> 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>
    John Machin, Feb 11, 2009
    #4
  5. Matthew Sacks

    John Machin Guest

    On Feb 11, 4:36 pm, Matthew Sacks <> wrote:
    > 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:
    >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
    >>> args = s.split()
    >>> args

    ['--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.
    John Machin, Feb 11, 2009
    #5
  6. 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

    On Tue, Feb 10, 2009 at 10:36 PM, John Machin <> wrote:
    > On Feb 11, 4:36 pm, Matthew Sacks <> wrote:
    >> 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:
    > >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
    > >>> args = s.split()
    > >>> args

    > ['--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.
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    Matthew Sacks, Feb 11, 2009
    #6
  7. Matthew Sacks

    John Machin Guest

    On Feb 11, 5:46 pm, Matthew Sacks <> wrote:
    > 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
    John Machin, Feb 11, 2009
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Arvind Kumar

    Problem with Getopt

    Arvind Kumar, Nov 3, 2003, in forum: Perl
    Replies:
    1
    Views:
    558
    Jim Gibson
    Nov 3, 2003
  2. dima
    Replies:
    9
    Views:
    686
    llewelly
    Sep 5, 2003
  3. Ramiro Rodriguez

    getopt

    Ramiro Rodriguez, Oct 14, 2003, in forum: C++
    Replies:
    6
    Views:
    3,991
    Lorenzo Bettini
    Oct 17, 2003
  4. Jem Berkes

    Re: Dealing with fragmented getopt parameters

    Jem Berkes, Oct 30, 2003, in forum: C Programming
    Replies:
    2
    Views:
    327
    Jem Berkes
    Oct 30, 2003
  5. Spartan815

    getopt

    Spartan815, Jan 25, 2004, in forum: C Programming
    Replies:
    2
    Views:
    1,064
    Peter Nilsson
    Jan 26, 2004
Loading...

Share This Page