473,836 Members | 1,568 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
20 5836
Steven Bethard <st************ @gmail.comwrite s:
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
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...@gmai l.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.comwrite s:
>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

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.Argume ntParser()
parser.add_ar gument('-1', dest='one', action='store_t rue')
args = parser.parse_ar gs(['-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.comwrite s:
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.comwrite s:
>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+hate s-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.comwrite s:
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+hate s-s...@benfinney. id.au>
wrote:
Steven Bethard <steven.beth... @gmail.comwrite s:
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

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

Similar topics

6
2792
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
8231
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
6126
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
3876
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
11958
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
35531
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
3744
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
4034
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
2315
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
9825
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
9671
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
10852
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10553
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
10596
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
10255
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
9382
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
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4459
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

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.