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:18:52 EST 2023
Jach Feng 在 2023年1月22日 星期日上午11:11:22 [UTC+8] 的信中寫道:
> 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!?
>
> --Jach
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="....")
The argparse has no complain at all, even I enter it in the command line.
e:\Works\Python>py infix2postfix.py "-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)))"
-4 2 ^ 5.3 -2 1 - abs * 2 / +
Abc abs B C + * D /
-3 1 x1 7 / y1 7 / * - sqrt * x0 4.5 - y0 4 - / abs sqrt *
But the happiness ends when this day comes,
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
Then, I know I am in trouble, and You know the rest of the story:-)
More information about the Python-list
mailing list