command-line parser

Trent Mick trentm at activestate.com
Sun Jun 18 18:11:25 EDT 2000


Cool. You know of the getopt module right? You could either just use *it* or
use it to simplify your implementation here. Some comments below.


On Sun, Jun 18, 2000 at 09:36:29PM +0000, Ben Wolfson wrote:
> """
> arglist.py
> 
> A utility for retrieving arguments passed via the command line.
> """
> 
> class Error(Exception):
>     pass
> 
>     
> class Arguments:
>     """
> Instantiate with tuples of acceptable options.  Tuples should have the form
> 
>     (short_form, long_form, accepts_value, default_value)
> 
> Either short_form or long_form can be None or a false value, if there is no
> short
> or long equivalent of the option, but not both (obviously).  If
> accepts_value is true
> and default_value is None, the instance will assume that a value is
> necessary, and
> raise Error if the option but no value is present.  Short_form and
> long_form should
> _not_ be passed with leading dashes.
> 
> __getattr__ is used to find out if an option is passed.  If the instance is
> instantiated as
> 
> >>> arg = arglist.Arguments(
>         ('h', 'help', None, None),
>         ('p', 'port', 1, 5555),
>         ('l', 'lalala', 1, None),
>         ('a', 'anotheropt', 1, 21)
>         )

I have often thought that getopt is nice but it would be nice to some kind of
OO approach where each "option" is like an object in that you can run its
"handle" method that will the processing/setup required for that options.

This could fit into your module by changing the above tuples into contructors
of an "Option" base class, or something like that

class OptionSpec:
	def __init__(short_form, long_form=None, accepts_value=0,\
		default_value=None, description=None):
		#...
	def handle():
		#...
	def help():
		"""print out standard formatted help for this option

		This could be helpful for creating automatic usage command line
		output."""
		#...

then 


>>> arg = arglist.Arguments(
        OptionSpec('h', 'help'),
        OptionSpec('p', 'port', 1, 5555),
        OptionSpec('l', 'lalala', 1),
        OptionSpec('a', 'anotheropt', 1, 21)
        )

A user could then also derived from the Option base class to have it do
special things.



Could


> 
> and the command line options are --port -l --anotheropt=haha
> 
> >>> arg.process(['--port', '-l:2', '--anotheropt=haha'])
> 
> then the following should result:
> 
> >>> arg.h
> >>> print arg.h
> None
> >>> arg.help
> >>> print arg.help
> None
> >>> arg.port
> 5555
> >>> arg.p
> 5555
> >>> arg.l
> '2'

Could maybe add type convertion, which would require type specification in
the Option contructor, so that the user could require that an integer or a
floating-poitn value be passed in.

<snip>



Cheers,
Trent

-- 
Trent Mick
trentm at activestate.com




More information about the Python-list mailing list