472,341 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,341 software developers and data experts.

optparse alternative

I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions. It allows you to
easily creating command line interfaces to existing functions, using
flags (which are optional) and arguments. It will automatically print a
nicely formatted usage (eg: -h or --help), and easily & automatically
validates parameter existence and type.

You can download it, and read a bit more about it, at
<http://hl.id.au/Projects/CommandLine/>

I'm interested in comments and criticisms; I've tried to write it
according to the python coding guildlines.

Example usage of a cmdline usage;

$ python test.py --help
Usage: test.py [OPTIONS] SOMEARG
An example to show usage of command line

Arguments
SOMEARG Some float argument

Mandatory arguments to long flags are mandatory for short options
too
-h, --help Show this help page
-s, --setflag Set the flag

Email bug reports to bu**@example.com

Source for the above example;

def someFunc(someArg, someFlag = False):
print "Flag value =", someFlag
print "Arg value =", someArg

from cmdline.Command import Command
command = Command(someFunc, "An example to show usage of command
line", "Email bug reports to bu**@example.com")
command.addFlag('s', 'setflag', 'Set the flag', 'someFlag')
command.addArgument('SOMEARG', 'Some float argument', 'someArg',
float)
command.invoke()

Normal use of test.py would have given

$ python test.py 3
Flag value = False
Arg value = 3.0

Jul 18 '05 #1
7 2705
Henry Ludemann wrote:
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions.


Looks interesting, but is it really that different from optparse?

I do like the fact that you can specify a type with a conversion
function. (In optparse, AFAIK, to add a new type you have to write your
own subclass of Option that screws with Option.TYPES and
Option.TYPE_CHECKER, which I've always thought was kinda nasty.)

But I wonder if it wouldn't be better to extend optparse with the
functionality instead of writing an entirely new module...

STeVe
Jul 18 '05 #2
Henry Ludemann wrote:
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions.


Some more detailed comments:

* The more I think about it, the more I like that you're basically
constructing options to match a function signature. But I can imagine
that this might be too restrictive for some uses. It might be worth
having an alternate interface that provides an options object like
optparse does.

* Any reason why you aren't using new-style classes?

* I think the code would be easier to navigate in a single module.

* Your code alternates between underscore_names and camelCaseNames.
Might be better to stick with one or the other. (PEP 8 suggests the
former.)

* File specific comments:

Argument.py:
Drop the get_name method; name attribute is already accessible. (The
property builtin makes getters and setters generally unnecessary.)

CommandArgument.py:
Drop the get_param_name method; param_name attribute is already accessible

Flag.py:
__init__ should have defaults where applicable (e.g. the comments say
you can provide None for short_flag, but it doesn't default to this).
Should also probably produce an error if neither short_flag nor
long_flag is set. (Or do this in Command._add_options)

In get_value, use "self.argument is None" not "self.argument == None".

get_flag_name should default to long_flag, not short_flag

Command.py:
add_flag should call _validate_param_name *before* _add_options (in case
an exception is raised and caught).

In _get_params,
for arg_index in range(len(method_args)):
arg = method_args[arg_index]
could be replaced with
for arg_index, arg in enumerate(method_args):

MulipleLines.py:
Can you use the (standard library) textwrap module instead? Seems like
they do about the same thing, but I haven't looked in too much detail.
Hope these comments are at least marginally useful. ;)

STeVe
Jul 18 '05 #3
Henry Ludemann wrote:
I've been writing an optparse alternative (using getopt) that is at a
stage where I'd be interested in people's opinions.


Thanks for the work and letting us see it!

As far as I can tell, your module has one functional advantage over
optparse--it validates arguments as well as options. The rest seems to
be cosmetics, and personally I prefer the cosmetics of optparse. For
one thing, it uses the variable/function naming style found throughout
most of the stdlib. optparse has also been widely used and tested for
the last four years.

I think you would be better off trying to extend optparse to deal with
non-option arguments, and you can tap into the installed base of
existing optparse users and even get your code included in the stdlib
if Greg Ward agrees. Whereas that's really unlikely for an entirely
new module--there just isn't the need for a THIRD way to do the same
thing.

Just a suggestion.
--
Michael Hoffman
Jul 18 '05 #4
Thanks for the comments...

Steven Bethard wrote:
Looks interesting, but is it really that different from optparse?
In the sense that they both do the same thing, no, not really. But the
way they do it is quite different; optparse bases itself on setting
variables, while this module is for invoking functions. I like this way
a better, as it acts as a more 'usual' client of the code, in the sense
that it uses publically exposed interfaces rather then internal
variables for passing the information. That said, the reason I started
this was that at the time I wasn't aware of optparse; my search through
the help needed to be a bit more thorough. When I found optparse, I
decided to continue on with this approach (mostly because I was having
fun with it).
I do like the fact that you can specify a type with a conversion
function. (In optparse, AFAIK, to add a new type you have to write
your own subclass of Option that screws with Option.TYPES and
Option.TYPE_CHECKER, which I've always thought was kinda nasty.)
Yeah, it works quite nicely; as it is a general function, you can use
your own methods for creating arbitrary objects (so long as they take
one parameter (a string)).
But I wonder if it wouldn't be better to extend optparse with the
functionality instead of writing an entirely new module...


The way of getting the data through to the program is quite different
(method vs data), so that would be a fairly radical change / addition
for optparse.

Jul 18 '05 #5

* The more I think about it, the more I like that you're basically
constructing options to match a function signature. But I can imagine
that this might be too restrictive for some uses. It might be worth
having an alternate interface that provides an options object like
optparse does.

It is matching options to a function signiture, and for complex methods,
this might be too restrictive (for example, you'd get methods with 10 -
20 params). That said, many cases don't have this many things that can
be set.

Although your point about providing an alternate interface is a good one...
* Any reason why you aren't using new-style classes?

Ignorance. I'll look into it...
* I think the code would be easier to navigate in a single module.

It might be easier to navigate (eg: when you want to go to a method
implmentation), but from a maintenance point of view I feel modular code
is easier... Mostly this is instint from other languages (mostly c++).
* Your code alternates between underscore_names and camelCaseNames.
Might be better to stick with one or the other. (PEP 8 suggests the
former.)

Yeah, I coded it before I looked at PEP8. Initially it was all camel
case, and I attempted to retrofit it. It seems like classes should still
be CamelCase, yes?
* File specific comments:

Argument.py:
Drop the get_name method; name attribute is already accessible. (The
property builtin makes getters and setters generally unnecessary.)

CommandArgument.py:
Drop the get_param_name method; param_name attribute is already
accessible

Flag.py:
__init__ should have defaults where applicable (e.g. the comments say
you can provide None for short_flag, but it doesn't default to this).
Should also probably produce an error if neither short_flag nor
long_flag is set. (Or do this in Command._add_options)

In get_value, use "self.argument is None" not "self.argument == None".

get_flag_name should default to long_flag, not short_flag

Command.py:
add_flag should call _validate_param_name *before* _add_options (in
case an exception is raised and caught).

In _get_params,
for arg_index in range(len(method_args)):
arg = method_args[arg_index]
could be replaced with
for arg_index, arg in enumerate(method_args):

Will do...

MulipleLines.py:
Can you use the (standard library) textwrap module instead? Seems
like they do about the same thing, but I haven't looked in too much
detail.

Doh! Yep, they do the same thing. This is another case of my not
checking the standard library well enough.
Hope these comments are at least marginally useful. ;)

Yes, very useful. Thanks very much for spending the time to go over it...

Jul 18 '05 #6
As far as I can tell, your module has one functional advantage over
optparse--it validates arguments as well as options.
Functionality wise, that is probably about it. It is more from a
seperation of command line / functionality code that I wrote this; that
the command line code should be seperate from the actual functional code.
The rest seems to be cosmetics, and personally I prefer the cosmetics
of optparse.
All to their own... I actually wrote this before I was aware of
optparse, and so didn't consider the benefits / disadvantages of that
way of doing it. It's simply a different approach. That said, what I
like about this approach is that it is non-obtrusive on the functional code.
For one thing, it uses the variable/function naming style found
throughout
most of the stdlib.
True... I originally wrote the code in camel case, and have attempted to
change it to the standard from PEP 8. I guess I missed a few things :-)
optparse has also been widely used and tested for
the last four years.
Again, true, but then again, this module (unlike optparse) uses the
standard getopt module for all command line parsing, which has been
around for even longer. So the bugs are all in the method invoking (my
code), and not in the parsing. <grin>
I think you would be better off trying to extend optparse to deal with
non-option arguments, and you can tap into the installed base of
existing optparse users and even get your code included in the stdlib
if Greg Ward agrees. Whereas that's really unlikely for an entirely
new module--there just isn't the need for a THIRD way to do the same
thing.
Yeah, a third module would be a bit redundent. I had actually written
most of this module before I became aware of optparse (it was one of
those bash the head against the wall moments when I found it), but
decided to continue with this version because I liked the cosmetics of
it (it seemed less intrusive on the functional code). Once it was more
or less finished, I decided to clean it up and post it in the hope it
might be useful to someone else, and perhaps more, to get any comments
that could improve it. And besides, variety is the spice of life :-)
Just a suggestion.


Thanks for your comments...
Jul 18 '05 #7
Henry Ludemann wrote:
I had actually written most of this module before I became aware
of optparse (it was one of those bash the head against the wall
moments when I found it),


I've been there :)
--
Michael Hoffman
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Hans-Joachim Widmaier | last post by:
I was really pleased when the Optik module found its way into the standard Python battery compartment, as it matched all my option parsing...
3
by: washu | last post by:
Hi, I'm was going through the module help located on http://docs.python.org/lib/optparse-store-action.html and I tried modifying it a tiny bit...
3
by: Karlo Lozovina | last post by:
If I create a file with only one line: --- from optparse import OptionParser --- I get this when I try to run it from "DOS" prompt: ...
3
by: Bob | last post by:
I'd like to setup command line switches that are dependent on other switches, similar to what rpm does listed below. From the grammar below we see...
0
by: Steven Bethard | last post by:
I feel like I must be reinventing the wheel here, so I figured I'd post to see what other people have been doing for this. In general, I love the...
1
by: Pupeno | last post by:
Hello, I am doing some extreme use of optparse, that is, extending it as explained on...
4
by: Mathias Waack | last post by:
We've integrated python into a legacy application. Everything works fine (of course because its python;). There's only one small problem: the...
2
by: mbeachy | last post by:
Some rather unexpected behavior in the set_default/set_defaults methods for OptionParser that I noticed recently: <Option at 0x-483b3414:...
0
by: Robert Kern | last post by:
Jeff Keasler wrote: If you code it up with unit tests and documentation, it has a good chance. But in the meantime, you can tell optparse to stop...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.