473,756 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

option argument length

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

I'm using optparse module to parse all options and arguments.

My program uses mostly "option arguments" hence my len(args) value is always
zero. I need to check if the user has passed the correct number of "option
arguments". Something like:

(options,args) = parser.parse_ar gs()

len(options) != 1 or len(options) > 2:
print "Incorrect number of arguments passed."

How do I accomplish it ?

Regards,

rrs
- --
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
"Stealing logics from one person is plagiarism, stealing from many is
research."
"Necessity is the mother of invention."

Note: Please CC me. I'm not subscribed to the list
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFDk1Nh4Rh i6gTxMLwRApx0AJ 9XHlWFU1J0NdN02 gtvimogUSgDkACg mkOO
2pX8ocoC7pot1a8 R4u2BWrY=
=piNo
-----END PGP SIGNATURE-----

Dec 4 '05 #1
9 2207
In <ma************ *************** ************@py thon.org>, Ritesh Raj
Sarraf wrote:
My program uses mostly "option arguments" hence my len(args) value is always
zero. I need to check if the user has passed the correct number of "option
arguments". Something like:

(options,args) = parser.parse_ar gs()

len(options) != 1 or len(options) > 2:
print "Incorrect number of arguments passed."

How do I accomplish it ?


Just insert an ``if`` in front of the condition and end the program with
``sys.exit()`` after the message.

Ciao,
Marc 'BlackJack' Rintsch
Dec 4 '05 #2
Ritesh Raj Sarraf wrote:
My program uses mostly "option arguments" hence my len(args) value is
always zero. I need to check if the user has passed the correct number of
"option arguments". Something like:

(options,args) = parser.parse_ar gs()

len(options) != 1 or len(options) > 2:
print*"Incorrec t*number*of*arg uments*passed."

How do I accomplish it ?


Judging from your code sample invention is the mother of that necessity.
You can pass a custom Values object with a __len__() method

class MyValues:
def __len__(self):
return len(self.__dict __)

# ...

options, args = parser.parse_ar gs(values=MyVal ues())

but you should do your users a favour and give them meaningful error
messages. I can't conceive how you could achieve this by checking the
number of options. Explicit constraint checks like

options, args = parser.parse_ar gs()
if options.eat_you r_cake and options.have_it :
parser.error("S orry, you cannot eat your cake and have it")

will increase your script's usability and make it easier to maintain for
only a tiny amount of work.

Peter

Dec 4 '05 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Marc 'BlackJack' Rintsch on Monday December 5 2005 03:24 wrote:
In <ma************ *************** ************@py thon.org>, Ritesh Raj
Sarraf wrote:
My program uses mostly "option arguments" hence my len(args) value is
always zero. I need to check if the user has passed the correct number of
"option arguments". Something like:

(options,args) = parser.parse_ar gs()

len(options) != 1 or len(options) > 2:
print "Incorrect number of arguments passed."

How do I accomplish it ?


Just insert an ``if`` in front of the condition and end the program with
``sys.exit()`` after the message.

Ciao,
Marc 'BlackJack' Rintsch


This won't help because "options" is an instance.

Regards,

rrs
- --
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
"Stealing logics from one person is plagiarism, stealing from many is
research."
"Necessity is the mother of invention."

Note: Please CC me. I'm not subscribed to the list
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFDlIbH4Rh i6gTxMLwRAlgSAJ 0Y3TT9eCBgrck5N 2Y9YjOTZMxUgwCc DeO5
qqgzY6rz2E4YKvu rnlHL0nQ=
=hlZO
-----END PGP SIGNATURE-----

Dec 5 '05 #4
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Peter Otten on Monday December 5 2005 03:34 wrote:
options, args = parser.parse_ar gs(values=MyVal ues())

but you should do your users a favour and give them meaningful error
messages. I can't conceive how you could achieve this by checking the
number of options. Explicit constraint checks like

options, args = parser.parse_ar gs()
if options.eat_you r_cake and options.have_it :
parser.error("S orry, you cannot eat your cake and have it")

will increase your script's usability and make it easier to maintain for
only a tiny amount of work.


I'm using this for "option arguments" which are mutually inclusive.
But I want the user to pass atleast one "option argument" for the program to
function properly.

For example, I have an option "--fetch-update" which requires a file "foo"
to check what it has to fetch. If the file is provided as an argument, it
uses it, else I add a parser.set_defa ults("foo") which makes the program to
look for it in the current working directory.

WHen the program see the "--fetch-update" option, it should execute the
required code. Now how do I check if at least one option has been passed at
the command-line ?
I have multiple options but I have parser.set_defa ults() for each of them.

Regards,

rrs
- --
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
"Stealing logics from one person is plagiarism, stealing from many is
research."
"Necessity is the mother of invention."

Note: Please CC me. I'm not subscribed to the list
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFDlIhF4Rh i6gTxMLwRAsLTAJ 9ydjppGrFVbH2kL 00vL00HgtrxqQCg hZBq
pC0/1HftWE+9Eipx6vF +3Bo=
=Ay8m
-----END PGP SIGNATURE-----

Dec 5 '05 #5
Ritesh Raj Sarraf wrote:
I'm using this for "option arguments" which are mutually inclusive.
But I want the user to pass atleast one "option argument" for the program
to function properly.

For example, I have an option "--fetch-update" which requires a file "foo"
to check what it has to fetch. If the file is provided as an argument, it
uses it, else I add a parser.set_defa ults("foo") which makes the program
to look for it in the current working directory.

WHen the program see the "--fetch-update" option, it should execute the
required code. Now how do I check if at least one option has been passed
at the command-line ?
I have multiple options but I have parser.set_defa ults() for each of them.


I'm sorry I don't understand your example. Wouldn't you need at least two
options to demonstrate "mutually inclusive" options? The set_default()
method seems to accept only keyword arguments -- but even it were used
correctly I'm still unclear why you would need it at all.

Perhaps you can post a few sample invocations (both correct and illegal) of
your script together with a description (in English, not code) of how the
script should react?

Peter, puzzled

Dec 6 '05 #6
On Tue, 6 Dec 2005, Peter Otten wrote:
Ritesh Raj Sarraf wrote:
I'm using this for "option arguments" which are mutually inclusive.
But I want the user to pass atleast one "option argument" for the program
to function properly.

For example, I have an option "--fetch-update" which requires a file "foo"
to check what it has to fetch. If the file is provided as an argument, it
uses it, else I add a parser.set_defa ults("foo") which makes the program
to look for it in the current working directory.

WHen the program see the "--fetch-update" option, it should execute the
required code. Now how do I check if at least one option has been passed
at the command-line ?
I have multiple options but I have parser.set_defa ults() for each of them.


I'm sorry I don't understand your example. Wouldn't you need at least two
options to demonstrate "mutually inclusive" options? The set_default()
method seems to accept only keyword arguments -- but even it were used
correctly I'm still unclear why you would need it at all.

Perhaps you can post a few sample invocations (both correct and illegal) of
your script together with a description (in English, not code) of how the
script should react?

Peter, puzzled

try:
version = "0.6b"
reldate = "03/10/2005"
copyright = "(C) 2005 Ritesh Raj Sarraf - RESEARCHUT (http://www.researchut. com/)"

#FIXME: Option Parsing
# There's a flaw with either optparse or I'm not well understood with it
# Presently you need to provide all the arguments to it to work.
# No less, no more. This needs to be converted to getopt sometime.

#parser = OptionParser()
#parser = optparse.Option Parser()
parser = optparse.Option Parser(usage="% prog [OPTION1, OPTION2, ...]", version="%prog " + version)
parser.add_opti on("-d","--download-dir", dest="download_ dir", help="Root directory path to save the downloaded files", action="store", type="string")
parser.set_defa ults(download_d ir="foo")
parser.add_opti on("-s","--cache-dir", dest="cache_dir ", help="Root directory path where the pre-downloaded files will be searched. If not, give a period '.'",action="st ore", type="string", metavar=".")
parser.set_defa ults(cache_dir= ".")
#parser.set_def aults(cache_dir =".")
#parser.add_opt ion("-u","--uris", dest="uris_file ", help="Full path of the uris file which contains the main database of files to be downloaded",act ion="store", type="string")

# We'll have additional options
# --set-update - This will extract the list of uris which need to be fetched
# --fetch-update - This will fetch the list of uris which need for update.
# --install-update - This will install the fetched database files
# The same will happen for upgradation.
# --set-upgrade - This will extract the list of uris which need to be fetched
# --fetch-upgrade - This will fetch the list of uris which need for upgrade
# --install-upgrade - This will install the fetched database files
parser.add_opti on("","--set-update", dest="set_updat e", help="Extract the list of uris which need to be fetched for _updation_", action="store", type="string", metavar="foo")
parser.set_defa ults(set_update ="foo")
parser.add_opti on("","--fetch-update", dest="fetch_upd ate", help="Fetch the list of uris which are needed for _updation_.", action="store", type="string", metavar="foo")
parser.set_defa ults(fetch_upda te="foo")
parser.add_opti on("","--install-update", dest="install_u pdate", help="Install the fetched database files ", action="store", type="string", metavar="foo.zi p")
parser.set_defa ults(install_up date="foo.zip")
parser.add_opti on("","--set-upgrade", dest="set_upgra de", help="Extract the list of uris which need to be fetched ", action="store", type="string", metavar="foo.da t")
parser.set_defa ults(set_upgrad e="foo.dat")
parser.add_opti on("","--fetch-upgrade", dest="fetch_upg rade", help="Fetch the list of uris which are needed ", action="store", type="string", metavar="foo.da t")
parser.set_defa ults(fetch_upgr ade="foo.dat")
parser.add_opti on("","--install-upgrade", dest="install_u pgrade", help="Install the fetched packages ", action="store", type="string", metavar="foo-fetched.zip")
parser.set_defa ults(install_ug prade="foofetch ed.zip")
(options, args) = parser.parse_ar gs()
#parser.check_r equired("-d", "-s", "-u")
#if len(arguments) != 2:
# parser.error("E rr! Incorrect number of arguments. Exiting")
if len(options) != 1 or len(options) > 2:
print len(args)
parser.error("N o arguments were passed\n")
sys.exit(1)
elif not options.set_upg rade and options.upgrade _type:
parser.error("O nly options --set-upgrade and --upgrade-type are mutually inclusive\n")
sys.exit(1)
Thanks,

rrs
--
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
"Stealing logic from one person is plagiarism, stealing from many is research."
"Necessity is the mother of invention."

Dec 7 '05 #7
Ritesh Raj Sarraf wrote:
parser.add_opti on("-d","--download-dir", dest="download_ dir",
help="Root directory path to save the downloaded files",
action="store", type="string")
parser.set_defa ults(download_d ir="foo")
This can be simplified to

parser.add_opti on("-d", "--download-dir", default="foo",
help="Root directory path to save the downloaded files")

which seems to be the reason why I've never seen the set_defaults() call
before.
if len(options) != 1 or len(options) > 2:


It doesn't matter much as it won't work anyway, but

len(options) > 2 implies len(options) != 1, so

if len(options) != 1:
#...

would suffice here.

Now to the actual problem: I think you didn't understand my previous
question. I cannot infer from your non-working code what it actually should
do. I asked for examples of how your script would be used. E. g,
assuming the code above is in a file called sarraf.py, what should the
following invocations

../sarraf.py --fetch-update bar
../sarraf.py --fetch-update bar --the-mutually-inclusive-option baz

do? Would the first terminate with an error message that another option must
also be given? Would it use the default? Would the second be accepted? Try
to describe it as simple and clear as possible. Imagine you were talking to
someone who has never written a line of code.

Peter
Dec 7 '05 #8
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi Peter,
Peter Otten on Wednesday December 7 2005 21:25 wrote:
This can be simplified to

parser.add_opti on("-d", "--download-dir", default="foo",
help="Root directory path to save the downloaded files")

which seems to be the reason why I've never seen the set_defaults() call
before.
As per python docs, it's mentioned that "default=" has been deprecated.
That's why I changed to parser.set_defa ults()
if len(options) != 1 or len(options) > 2:
It doesn't matter much as it won't work anyway, but

len(options) > 2 implies len(options) != 1, so

if len(options) != 1:
#...


Yes, you're right. Sorry.
would suffice here.

But will len(options) give a meaningful output. "options" is an instance.
It gives a Value Error.
Now to the actual problem: I think you didn't understand my previous
question. I cannot infer from your non-working code what it actually
should do. I asked for examples of how your script would be used. E. g,
assuming the code above is in a file called sarraf.py, what should the
following invocations

./sarraf.py --fetch-update bar
./sarraf.py --fetch-update bar --the-mutually-inclusive-option baz

do? Would the first terminate with an error message that another option
must also be given? Would it use the default? Would the second be
accepted? Try to describe it as simple and clear as possible. Imagine you
were talking to someone who has never written a line of code.


../sarraf.py --fetch-update /bar

If the user gives the /bar argument, the program should save the downloaded
files to /bar. But I'm assuming that the user could be dumb or too lazy, in
which case --fetch-udpate should use the parser.set_defa ults value
i.e. /foo

../sarraf.py --set-upgrade foo.dat --upgrade-type minimal

set-upgrade will again write data to foo.dat. If the user doesn't pass it as
an arguemnt it should take the defaults (again whatever is there in
parser.set_defa ults). This will be inclusive with the --upgrade-type option
because the user will have a choice of selecting what kind of upgrade he'd
like to do, minimal or full or blah.

For this I think this should be enough:

if not options.set_upg rade and options.upgrade _type:
parser.error("T hey are mutually inclusive options")
But my main concern is what if the user doesn't pass any arguemtns. Every
option I have has a default value. So I want to check what the user has
passed.
But unfortunately the args variable has "0" as its value always.

Is my way (up till now) of using optparse logically incorrect or improper ?
Regards,

rrs
- --
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
"Stealing logics from one person is plagiarism, stealing from many is
research."
"Necessity is the mother of invention."

Note: Please CC me. I'm not subscribed to the list
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFDlzC84Rh i6gTxMLwRAtCBAJ 9z5zDQ8oyx8Jy/rLe9JrwLII3xtAC fTaEV
VhMmj8OD+/p+yN/8wF6xe+8=
=atC6
-----END PGP SIGNATURE-----

Dec 7 '05 #9
Ritesh Raj Sarraf wrote:
./sarraf.py --fetch-update /bar

If the user gives the /bar argument, the program should save the
downloaded files to /bar. But I'm assuming that the user could be dumb or
too lazy, in which case --fetch-udpate should use the parser.set_defa ults
value i.e. /foo

./sarraf.py --set-upgrade foo.dat --upgrade-type minimal

set-upgrade will again write data to foo.dat. If the user doesn't pass it
as an arguemnt it should take the defaults (again whatever is there in
parser.set_defa ults). This will be inclusive with the --upgrade-type
option because the user will have a choice of selecting what kind of
upgrade he'd like to do, minimal or full or blah.

For this I think this should be enough:

if not options.set_upg rade and options.upgrade _type:
parser.error("T hey*are*mutuall y*inclusive*opt ions")
But my main concern is what if the user doesn't pass any arguemtns. Every
option I have has a default value. So I want to check what the user has
passed.
But unfortunately the args variable has "0" as its value always.
args are just the leftover arguments. For

../sarraf.py alpha --set-upgrade foo.dat beta

it would be ["alpha", "beta"].

---

I think your description is starting to make sense to me. Your user can
either update or upgrade but you cannot just check the value of e. g.
set_upgrade because you want to treat the default value and that same value
given on the command line differently.

If this is a correct assessment I don't think what you want is covered by
optparse. However, I hacked something together:

import optparse

parser = optparse.Option Parser()

parser.add_opti on("--alpha")
parser.add_opti on("--beta")

class Values(object):
def __init__(self):
self.__defaults = {}
def set_defaults(se lf, **kw):
self.__defaults .update(kw)
def __len__(self):
"""Number of options set by the user."""
return len(self.__dict __) -1
def __getattr__(sel f, name):
try:
return self.__defaults[name]
except KeyError:
raise AttributeError
def is_default(self , name):
"""Return True when the default fro option 'name'
wasn't overriden by the user"""
return name not in self.__dict__

values = Values()
values.set_defa ults(alpha="xxx ", beta="yyy")

options, args = parser.parse_ar gs(values=value s)

print "len(option s) =", len(options)
print "alpha =", options.alpha,
print "(using default)" * options.is_defa ult("alpha")
print "beta =", options.beta,
print "(using default)" * options.is_defa ult("beta")

Not particularly elegant but I'm not able to come up with something better
for the moment. Maybe you should just provide fewer defaults to the parser.
Or you could look into option callbacks for an alternate approach.
Is my way (up till now) of using optparse logically incorrect or improper
?


Well, as the optparse author points out, "required options" are a
self-contradictory term -- don't use them if you can avoid it. Would your
problem go away if you used two different scripts, one for updating and the
other for upgrading?

Peter

Dec 7 '05 #10

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

Similar topics

2
7987
by: Wim Roffal | last post by:
I want to insert an option into a select. I know you can do something like: - Myselect.options = new Option('Hello 3'); but that doesn't do what I want because it overwrites an existing option. I have the existing options ordered on alphabet and the new option should fit in on the right place. Of course I can move all the options that come after the new one, but I wondered if there is a smarter way to do this.
4
1821
by: Siemel Naran | last post by:
Hi. I have found one advantage of returning values through the argument list. It's that we have to store the return value. But when we return by value, we may forgot to store the return value. Consider, void f(int x, int& i); int i, j; f(1, i);
3
18589
by: Iain Hallam | last post by:
Hi. I've been using display:none on the style property of some <option> elements in my forms, which works fine with Mozilla - as expected it removes the option from my dropdown (although it still exists in the code). Is there an equivalent in IE? The reasoning behind this is that I want users to rank objects using a <select> for each place (see below), and to remove the choice of earlier objects from <select> drop-downs later in the...
5
17217
by: Harry Haller | last post by:
<select name="cboPlaces" id="cboPlaces"> <option value="3">Countryside</option> <option value="4">Forest</option> <option value="5">Mountain</option> <option value="6">Desert</option> <option value="7">Jungle</option> <option value="7">Swamp</option> <option value="8">River</option> <option value="12">Town</option> <option value="9">Sea</option>
10
4885
by: David | last post by:
Can anyone give me a quick code snippet (that is standards-based) for adding OPTION tags to a SELECT dynamically. I have no problem doing it in IE but I am kind of new to the whole standards world and can't figure out how to make it work in, for instance, Firefox. Right now the code I am using is as follows: newOpt=document.createElement('OPTION'); newOpt.id='optKeyword'; newOpt.label='Keyword';...
3
15619
by: Stewart | last post by:
Dear comp.lang.javascript, I have more than once wanted to manipulate the contents of select boxes dynamically, whilst the boxes contain <optgroup> tags. Manipulation of a select box containing only <option> tags is fairly easy and there is plenty of material on the net to assist with this. However, I have searched long and found the material on the subject of <optgroup> to be sparse, with a few posts here & there, but basically you're...
6
7130
by: cepera | last post by:
Hi guys! How I can retrieve "option value" info from select tag? I am using this code, but it is only let me get "name". I need to pass this value to second select tag. I found this code here: http://adamv.com/dev/javascript/http_request but they do not have any instructions how to retrieve option values. ----------JS------------
1
3474
by: bytesFTW99 | last post by:
I have been struggling with this for some time can anyone help out? just trying to have 3 dropdown boxes that fill depending on what is selected, then in some cases click a button and have the second set of 3 dropdown boxes be filled with the same values. thank you <head> <SCRIPT LANGUAGE="JavaScript" type="text/javascript"> var firstChoice2 = 0; var secondChoice2 = 0;
0
9455
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9869
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9838
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9708
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7242
isladogs
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...
1
3805
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
2
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.