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.co m
Source for the above example;
def someFunc(someAr g, someFlag = False):
print "Flag value =", someFlag
print "Arg value =", someArg
from cmdline.Command import Command
command = Command(someFun c, "An example to show usage of command
line", "Email bug reports to bu**@example.co m")
command.addFlag ('s', 'setflag', 'Set the flag', 'someFlag')
command.addArgu ment('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 7 2792
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_CHE CKER, 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
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_name s 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_op tions)
In get_value, use "self.argum ent is None" not "self.argum ent == 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(metho d_args)):
arg = method_args[arg_index]
could be replaced with
for arg_index, arg in enumerate(metho d_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
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
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_CHE CKER, 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. * 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_name s 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_op tions)
In get_value, use "self.argum ent is None" not "self.argum ent == 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(metho d_args)): arg = method_args[arg_index] could be replaced with for arg_index, arg in enumerate(metho d_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... 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...
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 requirements. But, as always, there's really nothing that does
all you ever want, especially when it comes to option parsing -
there's just too many schemes to handle them all comfortably.
With this program I'm working on, I started to recognize that not only
the functionality should be delegated to...
|
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 and things don't work. If someone could tell me
what I'm doing wrong, I'd appreciate it.
The script that works (based on the code on the webpage) is:
#!/usr/bin/env python
|
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:
Traceback (most recent call last):
File "optparse.py", line 1, in ?
|
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 that the "query-options" are dependent on the query switch,
{-q|--query}. Can "optparse" do this or do I have to code my own
"thing"? Thanks.
QUERYING AND VERIFYING PACKAGES:
rpm {-q|--query}
....
query-options
|
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 optparse interface, but it doesn't do any checks on the arguments.
I've coded something along the following lines a number of times:
class OptionArgParser(optparse.OptionParser):
def __init__(self, *args, **kwargs):
self.min_args = kwargs.pop('min_args', None)
self.max_args =...
| |
by: Pupeno |
last post by:
Hello,
I am doing some extreme use of optparse, that is, extending it as explained
on
http://docs.python.org/lib/optparse-other-reasons-to-extend-optparse.html
I have subclassed OptionParser and Option. MyOptionParser uses MyOption as
option_class and in Python 2.4 it works. But I have to target Python 2.3.
In Python 2.3 the help and version options seem to be created before even a
parser is created and they are created using a hardcoded...
|
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
application reads the commandline and consumes all arguments prefixed with
a '-' sign. Thus its not possible to call a python module from the
commandline with a parameter list containing options prefixed by '-'
or '--' signs. Thats not a major problem, but it prevents us from using th
optparse...
|
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: -r/--restart>
{'restart': None}
{'retart': False, 'restart': None}
Why does set_default not raise an exception when passed a key that it
doesn't recognize?
|
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 processing options using the
standard "--" marker. For example:
$ cat mycommand.py
import optparse
parser = optparse.OptionParser()
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |