Getargs.py
HTML Documentation for getargs.py.
This is the official documentation for getargs.py,
a command-line argument-parsing module for Python.
MODULE: getargs
Generalized option handling for Python programs.
USAGE
from getargs import *
-
Set the variable 'progname' to sys.argv[0];
-
define any functions you may need in the arglist;
-
create an argument list of the form
arglist = (
( 'i', 0, "An integer argument", None ),
( 'f', 0.0, "A Float argument", 3.14159 ),
...
)
Instantiate a class arguments variable:
xarg = arguments ( '-', arglist )
Call the xarg.getargs() method:
progname, sys.argv = xarg.getargs ( sys.argv )
To query an option, use the value() method:
if xarg.value ( 'i' ) != None :
do something. ...
Boolean options have only two possible values, 1
or 0; if two or more options are mutually exclusive, it is the programmer's
responisibility to see that the exclusivity is maintained, using the setvalue()
method:
if xarg.value ( 'j' ) :
xarg.setvalue ( 'g', 0 )
ARGLIST FIELDS
Arglist fields are:
( key, type, docstring, value, mode )
where:
-
key = A single letter or a fullword
used to find the option in sys.argv
-
type = one of:
-
None == A boolean option; these keys take
no arguments;
-
0j == Autoincrementing flag; -i gives value
1, -iii gives value 3, etc.
-
0 == Requires an integer argument;
-
0L == Requires a long integer argument (may
end in 'L';
-
0.0 == Requires a floating point argument;
integer, but not long, strings are converted into floats;
-
nofile = Requires a filename argument, or
one of "stdin", "stdout" or "stderr";
-
nofunc = Value must be a valid function;
takes no arguments;
-
() == Requires a list of arguments, usually
of the form 'a b c d e', which is returned as a tuple
-
[] == Requires a list of arguments, usually
of the form 'a b c d e', which is returned as a list
-
docstring = String that represents
the hint the user sees, as in:
"Print a help message and exit"
-
value = The default value; if this
is not provided, None will be used.
-
mode = Used for file options only;
provides the second argument to open(); defaults to "r".
SINGLE LETTER OPTIONS
Single letter options that take arguments (non-boolean)
may do so in one of two ways, either immediately following the keyletter
('-i29') or following a space ('-i
29'). The choice is the user's, not the programmer's.
Single letter options of the autoincrementing variety have a default value
of 0. Each repetition of the keyletter in the option arguments increments
the flag value by one. "-i" has a value of 1, while "-iiii" has a
value of 4, for example.
LONG OPTIONS
Long options that take arguments (non-boolean) may
do so in one of two ways, either separated by a space ('-integer
29') or separated by a separator character,
by default the '=' sign ('-integer=29').
Again, the choice is left to the user, not the programmer. Autoincrementing
long options are not supported.
LIST AND TUPLE ARGUMENTS
Options that require list or tuple arguments need
such an argument in the form of a list, which probably needs to be quoted.
By default, the list has the form
'a b c d e f'
but by using the setsep() method the programmer
can have it be of the form
'a,b,c,d,e,f'
for example.
ORDER OF OPTIONS
The order of options is not significant. You cannot
tell if one option has been set on the command line before another; this
should not be a problem.
CASE
The case of options is significant; 'i'
and 'I' are different options, and
so are '-integer' and '-Integer'
(and also '-inTegeR'). However,
on long options, the user only needs to provide sufficient information
in order to set or toggle an option. The matching algorithm searches for
whatever substring the user provides; if the substring matches more than
one option, then it looks first for an exact match. Failing that,
it will match the longest option name it can for the substring provided.
I.e., if there are two options -h
and -help, and the user types '-he',
then the option matched will be -help.
FILE OPTIONS
The type of these is determined by matching against
the value 'nofile', which is defined
to be the same as the value returned by 'open("/dev/null", "r")';
if users are on a PC or on a Mac, they won't have "/dev/null",
so "nul" is used instead.
DETERMINING IF AN OPTION HAS APPEARED ON THE COMMAND
LINE
If the programmer provides a default value
other than None, then there is no way to tell if the option appeared
on the command line. However, if the default value is None, then
the value() method will return non-None if and only if the
user put it in the command line. This even works for boolean options, since
the only way for one to be set this way is in the arglist; all other methods
set the value to either 0 or 1. Autoincrementing options will have
the value 0 if they did not appear on the command line.
VARIABLES
The only variables in the getargs module are 'nofile',
which is used only to find the type of file options, and VERSION, which
can be found below.
FUNCTIONS
Functions provided by the getargs module are:
| nofunc() |
Provided to find the type of function
options. |
| isnumber() |
Used to determine if a string can
be converted into an integer; the string can contain only digits or '-'
or '+'. |
| islong() |
Same as isnumber(), except
the string can also contain the letter 'L'. |
| isfloat() |
The string contains digits, a period,
signs or the letters 'e' or 'E'. |
| manpage() |
Returns the __doc__ attribute
for the getargs module. |
CLASS
The only class provided by getargs is class arguments.
METHODS
The methods provided by the arguments class
are:
-
__init__ ( self, c = '-', a = ( ) ) : where
c = switch character for options. a = an arglist
as defined above.
-
__del__ ( self ) :
closes any open files.
-
__repr__ ( self ) :
Returns a string that can be used to display
short help to the user.
-
options ( self ) :
Returns a string of option letters or option
words, suitably separated if need be, for use in a "Usage" message.
-
argtype ( self, let ) :
Returns a string representing the argument type
expected by the option. This can be one of:
-
"#" for integers and longs;
-
"*" for autoincrementers;
-
"#.#" for floats;
-
"" for filenames for file options;
-
"
" for lists and tuples;
-
"" for everything else.
This method is used in __repr__.
-
has_key ( self, let ) :
Returns 1 if the option key let was defined
in the arglist, or 0 if it has not.
-
additem ( self, let, typ, str, v = None,
mode = "r" ) :
Adds a new option and fields to an existing
arguments class variable, where:
-
let = The option letter or word;
-
type = the type (0, 0L, etc.)
-
v = default value;
-
mode = second argument to open().
Used internally; you shouldn't ordinarily need to
use this.
-
type ( self, let ) :
Returns either the type of option ("",
etc.) or None if there is no such option.
-
value ( self, let ) :
Returns either the value of the option (0, 49L,
etc.) or None if there is no such option.
-
mode ( self, let ) :
Returns either the mode to be used in opening
the file or None if there is no such option.
-
file ( self, let ) :
If there is no such option, returns None. Otherwise,
returns the filename, the mode, and the file pointer (fname,mode,fp); the
file pointer is either None, in which case the open() method needs to be
called, or an already open file pointer which may be used directly.
-
open ( self, let ) :
If this is a file option and the option exists,
performs an open() on the filename using the stored mode. Returns None
if the option doesn't exist or if open() returns None.
-
close ( self, let ) :
If this is a valid option and the file pointer
is open, fflushes it and closes it. There is no return value. Automatically
called by the __del__ method, so you don't always need to do this.
-
docstring ( self, let ) :
Returns the docstring, if there is one and if
let is a valid option.
-
len ( self ) :
Returns the number of options currently defined.
-
keys ( self ) :
Returns a _sorted_ list of the options. If there
are no options currently defined, returns None.
-
longest ( self ) :
Returns 0 or the len() of the longest option
string.
-
longestargtype ( self ) :
Returns 0 or the len() of the longest argtype
string used by the current set of options.
-
switchchar ( self ) :
Returns the switch character, which is '-' by
default.
-
setswitch ( self, let ) :
Sets the switch character (the option lead-in
character) to let: on PCs, for example, you could set this to '/'.
-
sepchar ( self ) :
Returns the list separator character, which
is ' ' by default.
-
setsep ( self, c ) :
Sets the list separator character to c; a good
alternate for this might be ','.
-
parenchar ( self ) :
Returns the character used to separate option
letters or words from their docstrings when building the __repr__ string.
-
setsep ( self, c ) :
Sets the option separator character to c; for
example, setting this to ']' would result in
-h] Help
instead of
-h) Help
eqchar ( self ) :
Returns the character that separates long options
from their values, which is set to '=' by default.
seteq ( self, c ) :
Sets the long option value separator character
to c; it's not a good idea to set this to ' '.
setvalue ( self, c, v ) :
If c is a valid option, this method checks the
type of v with the required type of c. The value indicated by v may not
be None. Attempting to set an improper value prints an error message and
otherwise does nothing.
setargs ( self, list ) :
If list is a list of the form ( ( let, type,
docstring, ... ), ... ), then setargs() runs through the outer list and
uses the elements of the inner lists as parameters to the additem() method.
matchlongarg ( self, m ) :
It's better not to use this; it's used internally
by the getargs() method, where the context is set correctly. What it does
is look through all the options to see if it can make a match with m; not
all characters have to match exactly. If m is 'long', for example, and
there are options 'l', 'lo' and 'longest', then matchlongarg() will return
'longest' as its best choice. The return value can then be used as an option
key in, say, setvalue().
getargs ( self, argv ) :
This is the interface between the option list
(well, actually a dictionary of dictionaries) and the program's command
line. The proper way to use this method is (for example):
xarg = arguments ( '-', arglist )
progname, sys.argv = xarg.getargs ( sys.argv )
After which sys.argv[ 0 ] and all options
between argv[ 0 ] and the first non-option argument will be consumed,
leaving the program responsible for any remaining command-line parameters.
Values of any of the options that were consumed may be obtained through
the value() method.
HISTORICAL NOTE
I first built a version of getargs in C many
years ago, but I no longer support the C version; I never released it because
I was never satisfied with it, and because it was much too delicate for
public performance. Also, because it was written in C (not C++), it could
be very complicated to use. The Python version cures all those problems,
although I recognize that it's probably more complicated than some people
would like. I'm always open to simplification suggestions.
BUGS AND SPECIAL CONSIDERATIONS
Functions referred to in arglist must be defined
before the arglist. The program name (progname) must be defined (as in
"progname = sys.argv[ 0 ]") before
you can use it in any function referred to in the arglist. Such functions
are called as soon as they are found in the command line.
There's no way to specify complex numbers on
the command line, and no complex argument type. This will eventually
be remedied.
While there is no way to tell if any option has
been set before any other option, the parser does proceed in a linear manner;
i.e., "-out foo -help" would actually
set the "-out" value "foo"
before the "-help" function was
called. Not that there's much utility in that.
Report any bugs found to ivanlan@callware.com.
Report any infelicitous grammar or language errors in this __doc__
attribute or HTML page to the same place.
Thank you for using getargs.
COPYRIGHT
Copyright 1994, 1995, 1996, 1997, 1998, 1999 by
Ivan Van Laningham.
All rights reserved.
License granted to anyone for non-commercial
use, as long as this copyright notice and the author's name are included
in any modifications, and such modifications are reported to the author
for consideration in future releases.
VERSION
Version 1.3, 12.19.6.11.6 13 Kimi
14 Yax G1 11:11:01
EXAMPLE
Here's a complete test program in Python:
#!/usr/local/bin/python
#
# Copyright 1999
# by Ivan Van Laningham
# All Rights Reserved.
#
import sys
import os
import time
import math
import string
from getargs import *
if __name__ == "__main__" :
progname = sys.argv[ 0 ]
def printversion ( l = 0 ) :
print "Version 1.%s" % ( l )
def man ( l = 0 ) :
print manpage ( )
sys.exit ( 0 )
def helpPig ( l = 0 ) :
print "%s: Usage %s any old gunk" % ( progname, xarg.options ( ) )
print xarg,
print "I'm Porky Pig"
sys.exit ( 0 )
def helpHog ( l = 0 ) :
print xarg,
print "I'm a HAWG!"
arglist = ( ( 'v', nofunc, "Function (print version)", printversion ),
( 'M', nofunc, "Man page", man ),
( '-manual', nofunc, "Man page", man ),
( 'i', 0, "Integer", None ),
( 'f', 0.0, "Float", None ),
( '+snorgle', "", "A Fubar String", None ),
( 'tuple', ( ), "Nameless tuple", None ),
( 'q', None, "None test", None ),
( 'list', [ ], "Nameless list", None ),
( 'h', nofunc, "Help", helpPig ),
( 'hogs', nofunc, "Help", helpHog ),
( 'qln', 0L, "Funky Long", None ),
( '-longarg', None, "Boolean long argument" ), # Adding leading - provides --longarg syntax. ...
( '-output', nofile, "the output file", "/tmp/dogbone" ),
( '-longest', None, "Boolean long argument" ), # Adding leading - provides --longarg syntax. ...
( '-longerlongerandlonger', 0, "Integer long argument", None ), # Adding leading - provides --longarg syntax. ...
)
xarg = arguments ( '-', arglist )
progname, sys.argv = xarg.getargs ( sys.argv )
helpHog ( )
q = xarg.keys ( )
for ii in q :
print ii, xarg.value ( ii )
o = 0
for n in range ( len ( sys.argv ) ) :
print o, sys.argv[ n ]
o = o + 1
AVAILABILITY
You can download getargs.py, testarg.py
and this file, getargs.html at:
Copyright
© 1999 Ivan Van Laningham
ivanlan@callware.com