On 21Jan2023 19:11, Jach Feng <jf...@ms4.hinet.net> 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

The usual convention for having "nonoption" arguments beginning with a dash/minus is to explicitly _end_ the option arguments, eg:

    py infix2postfix.py -- "-4^2+5.3*abs(-2-1)/2"

That "--" indicates the end of the options, and that what follows should not be treated as an option. _However_, it requires support in the script parsing the options. I'm pretty sure argparse gives that support for free, as does getopt and probably any others implementing "normal UNIXish options".

SO try adding a "--" argument and see how it behaves.

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

This is a different error. `parse_args()` expects a list of arguments, not a single argument. So it has iterated over what you gave it, which produces a series of single character strings which it has taken to be individual arguments. Try this:

    parser.parse_args(["-4^2+5.3*abs(-2-1)/2"])

and of course:

    parser.parse_args(["--", "-4^2+5.3*abs(-2-1)/2"])

You can see this behaviour of strings as:

    print(list("abc"))

or:

    for s in "abc":
        print("s =", repr(s))

Cheers,
Cameron Simpson <c...@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to