473,549 Members | 2,745 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Optparse: Detecting if option or option-arg is specified or not

I am using optparse for the commandline parsing for my programs. I
was wondering if it is possible to detect if an option or option-arg
has been specified on the commandline by the user or not. Please do
not suggest default value solutions.

Thanks.
Jul 18 '05 #1
4 3996
Sam Smith wrote:
I am using optparse for the commandline parsing for my programs. I
was wondering if it is possible to detect if an option or option-arg
has been specified on the commandline by the user or not. Please do
not suggest default value solutions.


What's wrong with default values?
Anyway, here's the hasattr() approach:
p = optparse.Option Parser()
p.add_option("-x", action="store_t rue") <optparse.Optio n instance at 0x403a1fcc> class NS: pass .... values = NS()
p.parse_args([], values) (<__main__.NS instance at 0x402c3f6c>, []) hasattr(values, "x") False p.parse_args(["-x"], values) (<__main__.NS instance at 0x402c3f6c>, []) hasattr(values, "x") True


Peter
Jul 18 '05 #2
>> What is wrong with default values?

Per-se there is nothing wrong with default values. But I think that
there should be some way for detecting if the user has specified a
specific option or option-arg on the commandline or not. Your
solution works in the sense that we are able to detect whether an
option or option-arg is specified or not, but now default value
assignment will not work.

What I really want is to specify an option having a default value
which could be specified by the user too. The user may decide to
specify this option on the commandline, and if not the option should
take the default value. But I should be able to query to find if this
setting of the value has been done due to optparse filling in default
value or it has been done by the user.

Usage Scenario:

I am implementing a multi-level commandline program. On windows
platform similar to "net /?" command which in turn has "net use /?",
"net computer /?" etc commandlines.

Some of my commandlines share the same option-arg, but the default
value to be associated with each of them is different. In one of the
commandlines I was trying to detect if the user has specified the
option or not and if not assign a different value to the option.

Irrespective of the usage scenario, I believe that it is important to
give the module user the ability to find out whether an option has
been specified or not by the user.

Some suggestions:

* Maybe a method can be added to the option class, isSpecified()
which will return True if the option is found on commandline
and optparse has read it or False if the option is not found
on the commandline.

* Add ability to query the Values instance which is returned by
parse_args

Thanks
Jul 18 '05 #3
Sam Smith wrote:
Some of my commandlines share the same option-arg, but the default
value to be associated with each of them is different. In one of
the commandlines I was trying to detect if the user has specified
the option or not and if not assign a different value to the option.
Perhaps you should wait to specify your options (i.e., populate your
Parser object) until you know which command you're dealing with.
Irrespective of the usage scenario, I believe that it is important
to give the module user the ability to find out whether an option
has been specified or not by the user.


I don't. I have yet to see a compelling example where such
introspection is really necessary.

But if you really do, then put it in post-processing. Set the default
value to something that cannot be specified on the command line, test
for that value, and proceed accordingly.

I'm pretty sure this topic has been hashed out thoroughly on the
optik-users mailing list
(http://sourceforge.net/mailarchive/f...forum_id=6064). I
suggest some research there and if you're still convinced, post there.
I doubt if Greg Ward (the author of Optik/optparse) will see your
posts here.

-- David Goodger
Jul 18 '05 #4
Sam Smith wrote:
Usage Scenario:

I am implementing a multi-level commandline program. On windows
platform similar to "net /?" command which in turn has "net use /?",
"net computer /?" etc commandlines.

Some of my commandlines share the same option-arg, but the default
value to be associated with each of them is different. In one of the
commandlines I was trying to detect if the user has specified the
option or not and if not assign a different value to the option.
I normally don't advocate code duplication, but in this case I'd either
specialcase

if specialcommandl ine:
parser.add_opti on(special option)
else:
parser.add_opti on(normal option)

or completely separate the parsers for the two differing scenarios.
Irrespective of the usage scenario, I believe that it is important to
give the module user the ability to find out whether an option has
been specified or not by the user.
Irrespective of the usage scenario - you can't be serious here.
Some suggestions:

* Maybe a method can be added to the option class, isSpecified()
which will return True if the option is found on commandline
and optparse has read it or False if the option is not found
on the commandline.

* Add ability to query the Values instance which is returned by
parse_args


My doubts not withstanding, here's how to achieve the desired (I think)
behaviour in a few lines - not tested beyond what you see as I will hardly
ever use it myself:

import sets
import optparse as op

class Values(op.Value s):
def __init__(self, defaults):
op.Values.__ini t__(self, defaults)
self.specified = sets.Set([])

def __setattr__(sel f, name, value):
self.__dict__[name] = value
if hasattr(self, "specified" ):
self.specified. add(name)
def test(args):
p = op.OptionParser ()
p.add_option("-f", dest="filename" , default="tmp.tx t")
v = Values(p.defaul ts)
p.parse_args(ar gs, v)
if "filename" in v.specified:
info = "specified: "
else:
info = "using default:"
print info, v.filename

test(["-f", "other.txt"])
test(["-f", "tmp.txt"])
test([])

Peter

Jul 18 '05 #5

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

Similar topics

8
2298
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...
5
1936
by: GMTaglia | last post by:
Hi guys, I was wondering why optparse accept an option if in the command line is not *exactly* the one present in the source code....may be an example will explain better.... #!/usr/bin/env python import optparse as opt
7
2779
by: Henry Ludemann | last post by:
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 &...
1
2850
by: sector119 | last post by:
Hi I use optparse with callback action, my callback function return some value, but optparse does not store this value, options.callback_dest always is None. How can I store callback function return value or callback option value like store action do? I modify optparse.py Option::take_action def and add there:
7
1698
by: R. Bernstein | last post by:
optparse is way cool, far superior and cleaner than other options processing libraries I've used. In the next release of the Python debugger revision, I'd like to add debugger options: --help and POSIX-shell style line trace (similar to "set -x") being two of the obvious ones. So I'm wondering how to arrange optparse to handle its...
3
2795
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} ...
1
1756
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...
4
1271
by: Shatadal | last post by:
In the python documentation section 14.3.2.6 (http://docs.python.org/ lib/optparse-generating-help.html) in the last line it is written "options that have a default value can include %default in the help string--optparse will replace it with str() of the option's default value. If an option has no default value (or the default value is...
3
2079
by: Dan | last post by:
I've been using optparse for a while, and I have an option with a number of sub-actions I want to describe in the help section: parser.add_option("-a", "--action", help=\ """Current supported actions: create, build, import, exp_cmd and interact. create -- Vaguely depreciated, should create a new project, but it is
0
912
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()
0
7520
marktang
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...
0
7450
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...
0
7720
Oralloy
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. ...
0
7957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7809
tracyyun
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...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1941
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
1
1059
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
763
bsmnconsultancy
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...

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.