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

Home Posts Topics Members FAQ

getopt with negative numbers?

Is there an easy way to use getopt and still allow negative numbers as
args? I can easily write a workaround (pre-process the tail end of
the arguments, stripping off any non-options including negative
numbers into a separate sequence and ignore the (now empty) args list
returned by getopt, but it would seem this is such a common
requirement that there would be an option to treat a negative value as
an argument. Note that this is only a problem if the first non-option
is a negative value, since getopt stops processing options as soon as
it identifies the first argument value.

Alternatively, does optparse handle this? I haven't used optparse (I
know it is more powerful and OO, but you tend to stick with what you
know, especially when it is part of my normal python programming
template), but if it handles negative numbers I'm willing to learn it.

Sep 27 '07 #1
20 5796
Casey wrote:
Is there an easy way to use getopt and still allow negative numbers as
args? I can easily write a workaround (pre-process the tail end of
the arguments, stripping off any non-options including negative
numbers into a separate sequence and ignore the (now empty) args list
returned by getopt, but it would seem this is such a common
requirement that there would be an option to treat a negative value as
an argument. Note that this is only a problem if the first non-option
is a negative value, since getopt stops processing options as soon as
it identifies the first argument value.

Alternatively, does optparse handle this? I haven't used optparse (I
know it is more powerful and OO, but you tend to stick with what you
know, especially when it is part of my normal python programming
template), but if it handles negative numbers I'm willing to learn it.
optparse can handle options with a negative int value; "--" can be used to
signal that no more options will follow:
>>import optparse
parser = optparse.Option Parser()
parser.add_op tion("-a", type="int")
<Option at 0xb7d6fd8c: -a>
>>options, args = parser.parse_ar gs(["-a", "-42", "--", "-123"])
options.a
-42
>>args
['-123']

Without the "--" arg you will get an error:
>>parser.parse_ args(["-123"])
Usage: [options]

: error: no such option: -1
$

Peter
Sep 27 '07 #2
On Sep 27, 1:34 pm, Peter Otten <__pete...@web. dewrote:
optparse can handle options with a negative int value; "--" can be used to
signal that no more options will follow:
Thanks, Peter. getopt supports the POSIX "--" end of options
indicator as well, but that seems a little less elegant than being
able to simply set a value that tells the parser "I don't use any
numeric values as options, and I want to allow negative values as
arguments". At the parser level implemening this would be trivial and
I frankly was hoping it had been implemented and it just wasn't
mentioned in the spares Python getopt library reference.

Sep 27 '07 #3
Casey wrote:
On Sep 27, 1:34 pm, Peter Otten <__pete...@web. dewrote:
>optparse can handle options with a negative int value; "--" can be used
to signal that no more options will follow:

Thanks, Peter. getopt supports the POSIX "--" end of options indicator
as well, but that seems a little less elegant than being able to simply
set a value that tells the parser "I don't use any numeric values as
options, and I want to allow negative values as arguments". At the
parser level implemening this would be trivial and I frankly was hoping
it had been implemented and it just wasn't mentioned in the spares
Python getopt library reference.
After a quick glance into the getopt and optparse modules I fear that both
hardcode the "if it starts with '-' it must be an option" behaviour.

Peter
Sep 27 '07 #4
If you can access the argument list manually, you could scan it for a negative integer, and then insert a '--' argument before that, if needed, before passing it to getopt/optparse. Then you wouldn't have to worry about it on the command line.

Cheers,
Cliff

On Thu, Sep 27, 2007 at 08:08:05PM +0200, Peter Otten wrote regarding Re: getopt with negative numbers?:
>
Casey wrote:
On Sep 27, 1:34 pm, Peter Otten <__pete...@web. dewrote:
optparse can handle options with a negative int value; "--" can be used
to signal that no more options will follow:
Thanks, Peter. getopt supports the POSIX "--" end of options indicator
as well, but that seems a little less elegant than being able to simply
set a value that tells the parser "I don't use any numeric values as
options, and I want to allow negative values as arguments". At the
parser level implemening this would be trivial and I frankly was hoping
it had been implemented and it just wasn't mentioned in the spares
Python getopt library reference.

After a quick glance into the getopt and optparse modules I fear that both
hardcode the "if it starts with '-' it must be an option" behaviour.

Peter
--
http://mail.python.org/mailman/listinfo/python-list
Sep 27 '07 #5
On Sep 27, 1:34 pm, Peter Otten <__pete...@web. dewrote:
....
>args

['-123']

Without the "--" arg you will get an error:
>parser.parse_a rgs(["-123"])

Usage: [options]

: error: no such option: -1
$

Peter
Passing -a-123 works
>>options, args = parser.parse_ar gs(["-a-123"])
options.a
-123

-N

Sep 27 '07 #6
On Sep 27, 2:21 pm, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
If you can access the argument list manually, you could scan it for a negative integer, and then insert a '--' argument before that,
if needed, before passing it to getopt/optparse. Then you wouldn't have to worry about it on the command line.

Cheers,
Cliff
Brilliant!

<code>
# Look for the first negative number (if any)
for i,arg in enumerate(sys.a rgv[1:]):
# stop if
if arg[0] != "-": break
# if a valid number is found insert a "--" string before it
which
# explicitly flags to getopt the end of options
try:
f = float(arg)
sys.argv.insert (i+1,"--")
break;
except ValueError:
pass
</code>

Sep 27 '07 #7
On Sep 27, 2:21 pm, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
If you can access the argument list manually, you could scan it for a negative integer,
and then insert a '--' argument before that, if needed, before passing it to getopt/optparse.
Then you wouldn't have to worry about it on the command line.

Cheers,
Cliff
Brilliant!

# Look for the first negative number (if any)
for i,arg in enumerate(sys.a rgv[1:]):
# stop if a non-argument is detected
if arg[0] != "-": break
# if a valid number is found insert a "--" string before it which
# explicitly flags to getopt the end of options
try:
f = float(arg)
sys.argv.insert (i+1,"--")
break;
except ValueError:
pass

Sep 27 '07 #8
Casey wrote:
Is there an easy way to use getopt and still allow negative numbers as
args?
[snip]
Alternatively, does optparse handle this?
Peter Otten wrote:
optparse can handle options with a negative int value; "--" can be used to
signal that no more options will follow:
>>>import optparse
parser = optparse.Option Parser()
parser.add_o ption("-a", type="int")
<Option at 0xb7d6fd8c: -a>
>>>options, args = parser.parse_ar gs(["-a", "-42", "--", "-123"])
options.a
-42
>>>args
['-123']
In most cases, argparse (http://argparse.python-hosting.com/) supports
negative numbers right out of the box, with no need to use '--':
>>import argparse
parser = argparse.Argume ntParser()
parser.add_ar gument('-a', type=int)
parser.add_ar gument('b', type=int)
args = parser.parse_ar gs('-a -42 -123'.split())
args.a
-42
>>args.b
-123
STeVe
Sep 27 '07 #9
Casey wrote:
On Sep 27, 2:21 pm, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
>If you can access the argument list manually, you could scan it for a
negative integer, and then insert a '--' argument before that,
if needed, before passing it to getopt/optparse. Then you wouldn't have
to worry about it on the command line.

Cheers,
Cliff

Brilliant!

<code>
# Look for the first negative number (if any)
for i,arg in enumerate(sys.a rgv[1:]):
# stop if
if arg[0] != "-": break
# if a valid number is found insert a "--" string before it
which
# explicitly flags to getopt the end of options
try:
f = float(arg)
sys.argv.insert (i+1,"--")
break;
except ValueError:
pass
</code>
One person's "brilliant" is another's "kludge".

Sep 28 '07 #10

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

Similar topics

6
2777
by: David Bear | last post by:
I'm stumped. Trying to follow the docs and .. failure. here's the args >>> args '-Middwb@mainex1.asu.edu -AKHAAM@prlinux+898 -CA --D2003-08-20-09:28:13.417 -Ff -Hprlinux --JTCPIP_NPF_TEST_DARS_PORTRAIT -NTCPIP_NPF_TEST_DARS_PORTRAIT --Pholdqueue -Qholdqueue -aacct -b2895 -d/var/spool/lpd/holdqueue -edfA898prlinux...
7
8210
by: pj | last post by:
Why does M$ Query Analyzer display all numbers as positive, no matter whether they are truly positive or negative ? I am having to cast each column to varchar to find out if there are any negative numbers being hidden from me :( I tried checking Tools/Options/Connections/Use Regional Settings both on and off, stopping and restarting M$...
5
6107
by: Subrahmanyam Arya | last post by:
Hi Folks , I am trying to solve the problem of reading the numbers correctly from a serial line into an intel pentium processor machine . I am reading 1 byte and 2byte data both positive and negative quantities . Can any one tell me what are the things i should bear in mind .
14
3846
by: José de Paula | last post by:
Is getopt() and its companions, commonly found in GNU libc and other Unices libc, part of the C standard? Another doubt: I have a switch inside a while loop; is there a way to break out of the loop from the switch without using goto? I mean: start: while(chr = fgetc(inputfile)) { switch(chr)
11
11913
by: tlyczko | last post by:
Hello Rob B posted this wonderful code in another thread, http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/c84d8538025980dd/6ead9d5e61be85f0#6ead9d5e61be85f0 I could not figure out how to reply to the thread per se using Google Groups and so please forgive me for cutting and pasting (I emailed him but he may not...
15
35464
by: jaks.maths | last post by:
How to convert negative integer to hexadecimal or octal number? Ex: -568 What is the equivalent hexadecimal and octal number??
11
3710
by: drtimhill | last post by:
I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled. For example, to get the last character in a string, I can enter "x". To get the 2nd and 3rd to last, I can enter x etc. This is fine. Logically, I should be able to enter x to get the last and next to last characters. However,...
39
3977
by: Frederick Gotham | last post by:
I have a general idea about how negative number systems work, but I'd appreciate some clarification if anyone would be willing to help me. Let's assume we're working with an 8-Bit signed integer, and that it contains no padding. Firstly, I realise that the MSB is known as the sign-bit, and that it indicates whether the number is positive...
1
2300
by: Daniel Mark | last post by:
Hello all: I am using getopt package in Python and found a problem that I can not figure out an easy to do . // Correct input D:\>python AddArrowOnImage.py --imageDir=c:/ // Incorrect input D:\>python AddArrowOnImage.py --imageDi
0
7546
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
6071
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...
1
5387
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...
0
5111
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...
0
3517
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...
0
3496
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1962
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
1082
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
784
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.