How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

Mats Wichmann mats at wichmann.us
Thu Jan 26 10:12:33 EST 2023


On 1/24/23 23:28, Jach Feng wrote:
> Chris Angelico 在 2023年1月25日 星期三下午1:16:25 [UTC+8] 的信中寫道:
>> On Wed, 25 Jan 2023 at 14:42, Jach Feng <jf... at ms4.hinet.net> wrote:
>>> I was happy working with argparse during implement my script. To save the typing, I used a default equation for testing.
>>>
>>> sample = "-4^2+5.3*abs(-2-1)/2, abs(Abc)*(B+C)/D, (-3) * sqrt(1-(x1/7)*(y1/7)) * sqrt(abs((x0-4.5)/(y0-4)))"
>>> parser = argparse.ArgumentParser(description='Convert infix notation to postfix')
>>> parser.add_argument('infix', nargs='?', default=sample, help="....")
>>>
>> You're still not really using argparse as an argument parser. Why not
>> just do your own -h checking? Stop trying to use argparse for what
>> it's not designed for, and then wondering why it isn't doing what you
>> expect it to magically know.
>>
>> ChrisA
> I just don't get what you mean?
> 
>> You're still not really using argparse as an argument parser. Why not just do your own -h checking?
> 
> Is a math equation not qualified as a command line "argument"? What criteria do you use when judging the quality of an "argument"?

The ancient UNIX concept, later codified in the POSIX international 
standard, is that if an argument begins with a '-' it specifies an 
option.  The three standard library CLI argument parsers (getopt, 
optparse and argparse) all follow this convention.  You're feeding it 
something that they will conclude is an option, but you have given 
argparse no information how to deal with such an option.  The advice 
you've been given is: this is built in behavior.  You don't want that 
behavior. Either "fool" the module somehow (quoting with leading spaces, 
use the special option identifier of a bare double dash indicating "end 
of options", etc.) - or just don't use a module that behaves in a way 
you don't like.





More information about the Python-list mailing list