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

Thomas Passin list1 at tompassin.net
Sun Jan 22 00:30:07 EST 2023


On 1/21/2023 10:11 PM, Jach Feng wrote:
> Fail on command line,
> 
> e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2"
> usage: infix2postfix.py [-h] [infix]
> infix2postfix.py: error: unrecognized arguments: -4^2+5.3*abs(-2-1)/2
> 
> Also fail in REPL,
> 
> e:\Works\Python>py
> Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import argparse
>>>> parser = argparse.ArgumentParser(description='Convert infix notation to postfix')
>>>> parser.parse_args("-4^2+5.3*abs(-2-1)/2")
> usage: [-h]
> : error: unrecognized arguments: - 4 ^ 2 + 5 . 3 * a b s ( - 2 - 1 ) / 2
> 
> Just can't figure out where is wrong!?

It just doesn't work like that.  If you download the package, there is 
only one python file, __init__.py.  This file contains one class.  It 
has a demo at the end, commented out.  If you uncomment those lines and 
run the file, you get a result printed.

These remarks are based on downloading the link for the source 
distribution from Pypi
(https://pypi.org/project/infix2postfix/).  When I installed it with 
pip, nothing seems to have gotten installed although pip went through 
the motions and claimed it was. So I just downloaded the source package.

The test expression is "-(a*b)+(c+d)-(a+b+c+d)".  The test output for 
this is "ab*-cd++ab+c+d+-".

If you substitute your expression, the result is

abs1-2-*2/3.5+2^4-

This may or may not be correct. I'm not sure but I think it's as 
intended except for reversing "3.5".  But maybe that's right, I'm not 
too sure.   Notice that this file is in its first release, version 0.0.1 
- the metadata that says it's 'Development Status :: 5 - 
Production/Stable' seems to be bogus.  So it may very well be buggy.

At any rate, if you want to use it in a program that can accept 
arguments, you will have to write that part yourself.  And the 
expression you feed it would need to be a single string, meaning it has 
to be quoted on the command line as you have done (although on Windows 
you should be using double quotes instead of single quotes).

As for argparse, it isn't doing what you want because you haven't told 
it what to do with the arguments.


More information about the Python-list mailing list