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

Jach Feng jfong at ms4.hinet.net
Mon Jan 23 20:58:42 EST 2023


2QdxY4Rz... at potatochowder.com 在 2023年1月24日 星期二凌晨2:47:12 [UTC+8] 的信中寫道:
> On 2023-01-22 at 18:19:13 -0800,
> Jach Feng <jf... at ms4.hinet.net> wrote: 
> 
> > 1) Modify the sys.argv by inserting an item '--' before parsing it, ie. 
> > sys.argv.insert(1, '--') 
> > args = parser.parse_args()
> Please don't do that. :-) 
> 
> In my mind, sys.argv belongs to Python, not the application. Instead, 
> pass a newly created argument list to parse_args: 
> 
> args = parser.parse_args(['--'] + sys.argv) 
> 
> This approach (adjusting the actual arguments) will work until your 
> program actually has options.
> > 2) By adding an extra space character before the leading '-' sign, ie. 
> > e:\Works\Python>py infix2postfix.py " -4^2+5.3*abs(-2-1)/2" 
> > -4 2 ^ 5.3 -2 1 - abs * 2 / + 
> > 
> > But no idea how it works? and if it can survive in a newer argparse version?:-)
> It works because argparse checks the first character of each argument, 
> and *doesn't* strip/trim whitespace. So "-x" looks like an option, and 
> " -x" looks an argument.
More pathonic, but don't work. The '--' must be at index 1:-)

>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
usage: [-h] infix
: error: unrecognized arguments: -4.3+5


More information about the Python-list mailing list