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 have to admit that I don't know the background upon which the argparse was
built. The good side is that I don't carry its historical knowledge ( or
burden?), that's why I can use it in a new way which may make someone feel
uneasy.
The reason I am still keep on using argparse on this "one positional argument
only" CLI app is that I can't see what advantage I can get when writing code to
handling sys.argv directly for the following two situations,
-----
e:\Works\Python>py infix2postfix.py
usage: infix2postfix.py [-h] infix
infix2postfix.py: error: the following arguments are required: infix
e:\Works\Python>py infix2postfix.py -h
usage: infix2postfix.py [-h] infix
Convert infix notation to postfix
positional arguments:
infix Put equations in quote if there is space in it and separate each
one with a comma, ie.
"-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)))"
optional arguments:
-h, --help show this help message and exit
-----
comparing with code using the argparse below,
import argparse
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',
help='Put equations in quote if there is space in it and separate each one with
a comma, ie. "{}"'.format(sample))
import sys
if len(sys.argv) > 1 and not '-h' in sys.argv:
....sys.argv.insert(1, '--')
args = parser.parse_args()
--
https://mail.python.org/mailman/listinfo/python-list