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

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Mon Jan 23 13:46:42 EST 2023


On 2023-01-22 at 18:19:13 -0800,
Jach Feng <jfong 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 information about the Python-list mailing list