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

Jach Feng jfong at ms4.hinet.net
Tue Jan 24 22:11:18 EST 2023


avi.e... at gmail.com 在 2023年1月25日 星期三清晨6:39:13 [UTC+8] 的信中寫道:
> If I understood the issue, the problem is the unary minus at the start of the expression. 
> 
> So if you know the expression is in that argument, would it make sense to pad it in one of many ways that are otherwise harmless? 
> 
> Could you put parens on both sides of "-4^2+5.3*abs(-2-1)/2": 
> 
> "(-4^2+5.3*abs(-2-1)/2)" 
> 
> Or perhaps place a zero in front as in the awkward case where it begins with a minus sign: 
> 
> "0 -4^2+5.3*abs(-2-1)/2" 
> 
> Some people suggest you ask the user to modify what they type in and such changes may work. Your program could also potentially diddle with argv and recognize it albeit as you allow calling a function like abs() I can easily imagine a potentially valid looking "-abs(...)..." that could look like -a followed by something. 
> 
> I see a deeper issue with interactions at the command shell level if parts of the arithmetic expression are evaluated or changed before python is even invoked. 
> 
> Then again, I may be misunderstanding the issue.
> -----Original Message----- 
> From: Python-list <python-list-bounces+avi.e.gross=gmai... at python.org> On Behalf Of Jach Feng 
> Sent: Tuesday, January 24, 2023 2:21 AM 
> To: pytho... at python.org 
> Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
> cameron... at gmail.com 在 2023年1月24日 星期二下午2:05:33 [UTC+8] 的信中寫道: 
> > On 23Jan2023 17:58, Jach Feng <jf... at ms4.hinet.net> wrote: 
> > >>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5']) 
> > >usage: [-h] infix 
> > >: error: unrecognized arguments: -4.3+5 
> > This error doesn't look like "-4.3+5 looks like an option" but instead 
> > "we don't expect any arguments after "infix". 
> > 
> > Not personally a fan of argparse myself, but then I have my own 
> > elaborate command line framework which generally uses getopt for the 
> > option stuff. 
> > 
> > Cheers, 
> > Cameron Simpson <c... at cskk.id.au> 
> Hmm, good to you. During experiments in these days, I had found argparse shows some strange/unstable behaviors in dealing with the leading '-' situation.
> -- 
> https://mail.python.org/mailman/listinfo/python-list
The user may not know any unix idiom, or even don't know Python. Ask them to add extra characters in their equations to avoid the argparse conflict is strange to me.


More information about the Python-list mailing list