473,698 Members | 2,432 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 5819
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
2784
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 -fTCPIP_NPF_TEST_DARS_PORTRAIT -hprlinux -j898 -kcfA898prlinux -l66 -nKHAAM -sstatus -t2003-08-20-09:28:13.000 -w80 -x0 -y0...
7
8220
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$ Query Analyer in betwixt, but no improvement.
5
6116
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
3865
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
11932
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 have time to check his email), and I am hoping someone might be able to tell me how I can change this...
15
35496
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
3727
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, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I...
39
4007
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 or negative (irrespective of which negative number system is used).
1
2308
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
8678
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
8609
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,...
0
8871
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
7737
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...
0
5861
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();...
0
4371
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...
1
3052
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
2333
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.