473,405 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

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 5760
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.OptionParser()
parser.add_option("-a", type="int")
<Option at 0xb7d6fd8c: -a>
>>options, args = parser.parse_args(["-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_args(["-123"])

Usage: [options]

: error: no such option: -1
$

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

-N

Sep 27 '07 #6
On Sep 27, 2:21 pm, "J. Clifford Dyer" <j...@sdf.lonestar.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.argv[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.lonestar.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.argv[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.OptionParser()
parser.add_option("-a", type="int")
<Option at 0xb7d6fd8c: -a>
>>>options, args = parser.parse_args(["-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.ArgumentParser()
parser.add_argument('-a', type=int)
parser.add_argument('b', type=int)
args = parser.parse_args('-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.lonestar.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.argv[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
Steven Bethard <st************@gmail.comwrites:
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.ArgumentParser()
>>parser.add_argument('-a', type=int)
>>parser.add_argument('b', type=int)
>>args = parser.parse_args('-a -42 -123'.split())
>>args.a
-42
>>args.b
-123
That would be irritating. I've used many programs which have numbers
for their options because it makes the most sense, e.g. 'mpage' to
indicate number of virtual pages on one page, or any number of
networking commands that use '-4' and '-6' to specify IPv4 or IPv6.

If argparse treats those as numeric arguments instead of options,
that's violating the Principle of Least Astonishment for established
command-line usage (hyphen introduces an option).

--
\ "I went to a general store. They wouldn't let me buy anything |
`\ specifically." -- Steven Wright |
_o__) |
Ben Finney
Sep 28 '07 #11
On Sep 27, 7:57 pm, Neal Becker <ndbeck...@gmail.comwrote:
One person's "brilliant" is another's "kludge".
Well, it is a hack and certainly not as clean as having getopt or
optparse handle this natively (which I believe they should). But I
think it is a simple and clever hack and still allows getopt or
optparse to function normally. So I wouldn't call it a kludge, which
implies a more clumsy hack. As you say, it is all a matter of
perspective.

Sep 28 '07 #12
Ben Finney wrote:
Steven Bethard <st************@gmail.comwrites:
>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.ArgumentParser()
>>parser.add_argument('-a', type=int)
>>parser.add_argument('b', type=int)
>>args = parser.parse_args('-a -42 -123'.split())
>>args.a
-42
> >>args.b
-123

That would be irritating. I've used many programs which have numbers
for their options because it makes the most sense, e.g. 'mpage' to
indicate number of virtual pages on one page, or any number of
networking commands that use '-4' and '-6' to specify IPv4 or IPv6.
Did you try it and find it didn't work as you expected? Numeric options
seem to work okay for me::
>>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-1', dest='one', action='store_true')
args = parser.parse_args(['-1'])
args.one
True

Argparse knows what your option flags look like, so if you specify one,
it knows it's an option. Argparse will only interpret it as a negative
number if you specify a negative number that doesn't match a known option.

STeVe
Sep 28 '07 #13
Steven Bethard <st************@gmail.comwrites:
Did you try it and find it didn't work as you expected?
No, I was commenting on the behaviour you described (hence why I said
"That would be irritating").
Argparse knows what your option flags look like, so if you specify
one, it knows it's an option. Argparse will only interpret it as a
negative number if you specify a negative number that doesn't match
a known option.
That's also irritating, and violates the expected behaviour. It leads
to *some* undefined options being flagged as errors, and others
interpreted as arguments. The user shouldn't need to know the complete
set of options to know which leading-hyphen arguments will be treated
as options and which ones won't.

The correct behaviour would be to *always* interpret an argument that
has a leading hyphen as an option (unless it follows an explicit '--'
option), and complain if the option is unknown.

--
\ "When I was a kid I used to pray every night for a new bicycle. |
`\ Then I realised that the Lord doesn't work that way so I stole |
_o__) one and asked Him to forgive me." -- Emo Philips |
Ben Finney
Sep 28 '07 #14
Ben Finney wrote:
Casey <Ca******@gmail.comwrites:
>Well, it is a hack and certainly not as clean as having getopt or
optparse handle this natively (which I believe they should).

I believe they shouldn't because the established interface is that a
hyphen always introduced an option unless (for those programs that
support it) a '--' option is used, as discussed.
I don't agree. First of all, what is 'established interface'? There are
precedents from well-known C and C++ libraries, such as 'getopt', 'popt',
and boost::program_options. IIRC, each of these will treat a negative
number following an option that requires a number as a number.

Besides this, the behavior I just described is really required. Otherwise,
numeric options are basically broken.
Sep 28 '07 #15
Ben Finney wrote:
Steven Bethard <st************@gmail.comwrites:
>Argparse knows what your option flags look like, so if you specify
one, it knows it's an option. Argparse will only interpret it as a
negative number if you specify a negative number that doesn't match
a known option.

That's also irritating, and violates the expected behaviour. It leads
to *some* undefined options being flagged as errors, and others
interpreted as arguments. The user shouldn't need to know the complete
set of options to know which leading-hyphen arguments will be treated
as options and which ones won't.

The correct behaviour would be to *always* interpret an argument that
has a leading hyphen as an option (unless it follows an explicit '--'
option), and complain if the option is unknown.
It was decided that practicality beats purity here. Arguments with
leading hyphens which look numeric but aren't in the parser are
interpreted as negative numbers. Arguments with leading hyphens which
don't look numeric and aren't in the parser raise errors. Sure, it's not
the pure answer, but it's the practical answer: "-123" is much more
likely to be a negative number than an option.

STeVe
Sep 28 '07 #16
On Sep 27, 10:47 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
I believe they shouldn't because the established interface is that a
hyphen always introduced an option unless (for those programs that
support it) a '--' option is used, as discussed.
Not "THE" established interface; "AN" established interface. There
are other established interfaces that have different behaviors. I'm a
pragmatist; I write software for users, not techies. I suspect most
users would expect a command like "abc -a -921 351 175" to treat the
"-921" as a negative integer and not abort the program with some
obscure error about option 921 not being known.
>
But I think it is a simple and clever hack and still allows getopt
or optparse to function normally.

Except that they *don't* function normally under that hack; they
function in a way contradictory to the normal way.
Again, it depends on who is defining "normal" and what they are basing
it on. I suspect many (probably most) users who are familiar with
command line input are unaware of the "--" switch which was mainly
designed to support arbitrary arguments that might have an initial
hyphen, a much broader problem than supporting negative values. I'm
not asking that the default behavior of getopt or optparse change;
only that they provide an option to support this behavior for those of
us who find it useful. Software libraries should be tools that support
the needs of the developer, not rigid enforcers of arbitrary rules.

Sep 28 '07 #17
Casey wrote:
Ben Finney wrote:
>I believe they shouldn't because the established interface is that a
hyphen always introduced an option unless (for those programs that
support it) a '--' option is used, as discussed.

Not "THE" established interface; "AN" established interface. There
are other established interfaces that have different behaviors. I'm a
pragmatist; I write software for users, not techies. I suspect most
users would expect a command like "abc -a -921 351 175" to treat the
"-921" as a negative integer and not abort the program with some
obscure error about option 921 not being known.
Glad I'm not alone in this. ;-) A user shouldn't have to go out of their
way to specify regular numbers on the command line, regardless of
whether they're positive or negative.

STeVe

Sep 28 '07 #18
On Sep 28, 9:51 am, Steven Bethard <steven.beth...@gmail.comwrote:
Ben Finney wrote:
Steven Bethard <steven.beth...@gmail.comwrites:
Argparse knows what your option flags look like, so if you specify
one, it knows it's an option. Argparse will only interpret it as a
negative number if you specify a negative number that doesn't match
a known option.
That's also irritating, and violates the expected behaviour. It leads
to *some* undefined options being flagged as errors, and others
interpreted as arguments. The user shouldn't need to know the complete
set of options to know which leading-hyphen arguments will be treated
as options and which ones won't.
The correct behaviour would be to *always* interpret an argument that
has a leading hyphen as an option (unless it follows an explicit '--'
option), and complain if the option is unknown.

It was decided that practicality beats purity here. Arguments with
leading hyphens which look numeric but aren't in the parser are
interpreted as negative numbers. Arguments with leading hyphens which
don't look numeric and aren't in the parser raise errors. Sure, it's not
the pure answer, but it's the practical answer: "-123" is much more
likely to be a negative number than an option.
What if (for example) you define a option "-3", and also accept
numerical arguments on the command line. Then you could get sudden
unexpected behavior if you input the wrong number:

"./hello -1" works ok.
"./hello -2" works ok.
"./hello -3" ... whoops, now the negative number is suddenly an
option.

Granted, it would be stupid for a program to do that, but it suggests
to me that it's probably a good idea to treat all negative numbers the
same. I.e. if there are any numerical options, then all negative
numbers are treated as options. If there are none, then negative
numbers are treated as numbers.
Carl Banks

Sep 28 '07 #19
On Sep 28, 6:19 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
Steven Bethard <steven.beth...@gmail.comwrites:
A user shouldn't have to go out of their way to specify regular
numbers on the command line, regardless of whether they're positive
or negative.

A user shouldn't have to go out of their way to know whether what they
type on a command line will be treated as an option or an argument.
I guess typing

../program --help

is out of the question.

Carl Banks

Sep 28 '07 #20
Carl Banks wrote:
On Sep 28, 9:51 am, Steven Bethard <steven.beth...@gmail.comwrote:
>It was decided that practicality beats purity here. Arguments with
leading hyphens which look numeric but aren't in the parser are
interpreted as negative numbers. Arguments with leading hyphens which
don't look numeric and aren't in the parser raise errors. Sure, it's not
the pure answer, but it's the practical answer: "-123" is much more
likely to be a negative number than an option.

What if (for example) you define a option "-3", and also accept
numerical arguments on the command line. Then you could get sudden
unexpected behavior if you input the wrong number:

"./hello -1" works ok.
"./hello -2" works ok.
"./hello -3" ... whoops, now the negative number is suddenly an
option.

Granted, it would be stupid for a program to do that, but it suggests
to me that it's probably a good idea to treat all negative numbers the
same. I.e. if there are any numerical options, then all negative
numbers are treated as options. If there are none, then negative
numbers are treated as numbers.
That's probably a good guideline. Anyone mixing numeric flags with
negative number arguments is asking for an exception of some sort. ;-)
I'm going to let it sit for a while and think about it, but I'll
probably make that change in the next release.

STeVe
Sep 28 '07 #21

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

Similar topics

6
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...
7
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...
5
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...
14
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...
11
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...
15
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
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...
39
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,...
1
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...
0
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...

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.