Mailing List Archive

How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
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
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Thomas Passin ? 2023?1?22? ?????1:30:39 [UTC+8] ??????
> 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.
Sorry to cause confusion here. I don't know there is a Pypi project with the same name infix2postfix.py:-(

Nevertheless, Is there anyway to make parse_args works?
>>> parser.parse_args("-4^2+5.3*abs(-2-1)/2")
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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!?

First, you need to add an argument to the parser, so that it expects an
argument:
>>> parser.add_argument("expression")

Secondly, `parse_args` expects a list of arguments. By passing a
string, it interprets each character as a separate argument (since
iterating over a string yields each character in turn). Here, I
intentionally leave off the initial hyphen because that's the next problem:
>>> parser.parse_args(["4^2+5.3*abs(-2-1)/2"])
Namespace(expression='4^2+5.3*abs(-2-1)/2')

Thirdly, an initial hyphen indicates an optional argument so, for
example if you pass "-l" it will expect a "-l" argument to be defined as
one of the valid options, and also complain that you haven't specified
the required expression:
>>> parser.parse_args(["-4^2+5.3*abs(-2-1)/2"])
usage: [-h] expression
: error: the following arguments are required: expression

If you need to pass a value starting with a "-" there are a couple of
options...

Perhaps it would be acceptable to represent it as "0-...":
>>> parser.parse_args(["0-4^2+5.3*abs(-2-1)/2"])
Namespace(expression='0-4^2+5.3*abs(-2-1)/2')

While mathematically equivalent, that might have different meaning for
whatever you're trying to do. Alternatively, a double hyphen indicates
that there are no more options and that anything else is positional
arguments even if they begin with a hyphen:
>>> parser.parse_args(["--", "-4^2+5.3*abs(-2-1)/2"])
Namespace(expression='-4^2+5.3*abs(-2-1)/2')

You wouldn't usually explicitly pass a list of arguments to `parse_args`
like that, but it can be useful for testing and experimentation.
Usually, you'd call `parse_args()` without any arguments, and it would
parse the arguments passed on the command-line when calling your script.
e.g. you'd call (from a Windows command prompt / Linux shell / etc.):
> ./convert_infix.py -- '-4^2+5.3*abs(-2-1)/2'
(it's probably a good idea to quote the expression, in case it includes
any characters which would be interpreted specially by the shell - e.g.
"*" without quotes usually expands to all matching files in the current
directory)

--
Mark.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 2023-01-22 00:30:07 -0500, Thomas Passin wrote:
> On 1/21/2023 10:11 PM, Jach Feng wrote:
> > 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
[...]
> > > > > 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 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.

It depends on the intended meaning. But I'm pretty sure that "5.3" is
supposed to be a floating point number and not (5 operatordot 3), so
it's wrong to split that apart. (Also it seems that the code treats
digits as operators, not operands?)

Also "abs(...)" is almost certainly intended to be a function call, so
it should be invoked after its parameters.

I think the correct output (using newlines as delimiters) would be:

-4
2
^
5.3
-2
1
-
abs
*
2
/
+

> 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.

It is at least too incomplete to be useful. It handles only single
letters as operands and treats everything else (except parentheses) as an operator, handling
only +, -, *, / and ^ correctly (actually, ^ is typically right
associative, so that's arguably wrong, too).

hp

--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | hjp@hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/22/2023 10:45 AM, Peter J. Holzer wrote:
>> 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.
> It is at least too incomplete to be useful. It handles only single
> letters as operands and treats everything else (except parentheses) as an operator, handling
> only +, -, *, / and ^ correctly (actually, ^ is typically right
> associative, so that's arguably wrong, too).

This script is basically useless without some documentation on the
intended inputs and outputs, and how to invoke it. The documentation
could (in the minimal case) have been included in docstrings and
comments within the script. As it is, the script seems tantalizing but
unusable.

Please document your work, even if it's just for yourself!

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Argparse is for parsing command line arguments and options.

If you just want to evaluate an Python expression, use eval( )

Your string isn$B!G(Bt valid Python due to order of operations, but -(4^2)+5.3*abs(-2-1)/2 is.

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Jach Feng <jfong@ms4.hinet.net>
Date: Sunday, January 22, 2023 at 11:24 AM
To: python-list@python.org <python-list@python.org>
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

Thomas Passin $B:_(B 2023$BG/(B1$B7n(B22$BF|(B $B@14|F|2<8a(B1:30:39 [UTC+8] $BE*?.CfUmF;!'(B
> 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://urldefense.com/v3/__https://pypi.org/project/infix2postfix/__;!!Cn_UX_p3!gqKmYLlyUndAzxmJsqCB429izQ-2-KMbpGP2eVzp_iDKtbgQXfrCu21UBvepq-F9EXb4SJwP516MHeUFMBtW$ ). 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.
Sorry to cause confusion here. I don't know there is a Pypi project with the same name infix2postfix.py:-(

Nevertheless, Is there anyway to make parse_args works?
>>> parser.parse_args("-4^2+5.3*abs(-2-1)/2")
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!gqKmYLlyUndAzxmJsqCB429izQ-2-KMbpGP2eVzp_iDKtbgQXfrCu21UBvepq-F9EXb4SJwP516MHezHygV-$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!gqKmYLlyUndAzxmJsqCB429izQ-2-KMbpGP2eVzp_iDKtbgQXfrCu21UBvepq-F9EXb4SJwP516MHezHygV-$>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 21Jan2023 19:11, Jach Feng <jfong@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 <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/22/23 11:44, Stefan Ram wrote:
> Jach Feng <jfong@ms4.hinet.net> writes:
>> e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2"
>
> Well, it's a nice exercise! But I only made it work for the
> specific example given. I have not tested whether it always
> works.

Haha. Yes a nice exercise, but has nothing to do with the original
question which is how to convince argparse to accept a string like that
without thinking it's a switch. Many unix utilities treat "--" as a
special argument that turns off argument parsing for the rest of the
command line. Maybe argparse follows this convention too; I don't know.
But if it did you'd do:

infix2postfix.py -- "-4^2+5.3*abs(-2-1)/2"
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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
Thank you for all your suggestions. From it, I get two solutions for my problem.

1) Modify the sys.argv by inserting an item '--' before parsing it, ie.
sys.argv.insert(1, '--')
args = parser.parse_args()

It works, and maybe more reliable.
e:\Works\Python>py infix2postfix.py "-4^2+5.3*abs(-2-1)/2"
-4 2 ^ 5.3 -2 1 - abs * 2 / +

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?:-)
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 2023-01-22, Weatherby,Gerard <gweatherby@uchc.edu> wrote:
> Argparse is for parsing command line arguments and options.
>
> If you just want to evaluate an Python expression, use eval( )

Only use eval() if the expression is always under your control (and
you don't make mistakes when typing).

Don't use eval() on strings that come from the outside world.

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 2023-01-22 at 18:19:13 -0800,
Jach Feng <jfong@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.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 23Jan2023 13:46, 2QdxY4RzWzUUiLuE@potatochowder.com <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
>On 2023-01-22 at 18:19:13 -0800,
>Jach Feng <jfong@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. :-)

Well... We routine mmodify argv when parsing a command line. It's just a
list. It does assume I'm the only user of it.

>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)

I do sometimes copy it:

def main(argv):
argv = list(argv)

for exactly the reasons you're alluding to. Then I'm free to modify the
copy.

But for Jach Feng: the "--" is really expected as something the user
does when they invoke your programme, _explicitly_ saying that what
follows from here is not an argument. So the user is expected to type:

your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"

where there are -x and -y options, then end of options, then an
argument, which would look like an option if there wasn't the "--"
argument.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <cs@cskk.id.au> wrote:
>
> But for Jach Feng: the "--" is really expected as something the user
> does when they invoke your programme, _explicitly_ saying that what
> follows from here is not an argument. So the user is expected to type:
>
> your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
>
> where there are -x and -y options, then end of options, then an
> argument, which would look like an option if there wasn't the "--"
> argument.

And if you DON'T expect the user to enter the "--", then why use
argparse? You can just check argv directly to get your arguments.

This entire thread is a massive "how can I use X to do Y?" problem.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
>> On 2023-01-22 at 18:19:13 -0800,
>> Jach Feng <jfong@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()

If you do that, you'll never be able to have any actual options, so
using argparse seems like overkill. Just pull the argument out of
argv directly.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
2QdxY4Rz...@potatochowder.com ? 2023?1?24? ?????2:47:12 [UTC+8] ??????
> On 2023-01-22 at 18:19:13 -0800,
> Jach Feng <jf...@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 pathonic, but don't work. The '--' must be at index 1:-)

>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
usage: [-h] infix
: error: unrecognized arguments: -4.3+5
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Chris Angelico ? 2023?1?24? ?????5:00:27 [UTC+8] ??????
> On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <c...@cskk.id.au> wrote:
> >
> > But for Jach Feng: the "--" is really expected as something the user
> > does when they invoke your programme, _explicitly_ saying that what
> > follows from here is not an argument. So the user is expected to type:
> >
> > your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
> >
> > where there are -x and -y options, then end of options, then an
> > argument, which would look like an option if there wasn't the "--"
> > argument.
> And if you DON'T expect the user to enter the "--", then why use
> argparse? You can just check argv directly to get your arguments.
>
> This entire thread is a massive "how can I use X to do Y?" problem.
>
> ChrisA
The '--' requirement makes its usage less instinctive, and handling argv directly makes me loss the benefit of using '-h':-)
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Greg Ewing ? 2023?1?24? ?????7:33:43 [UTC+8] ??????
> >> On 2023-01-22 at 18:19:13 -0800,
> >> Jach Feng <jf...@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()
> If you do that, you'll never be able to have any actual options, so
> using argparse seems like overkill. Just pull the argument out of
> argv directly.
>
> --
> Greg
Any easy way to "pull the argument out of argv directly" before parse_args()?:-)
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Tue, 24 Jan 2023 at 13:09, Jach Feng <jfong@ms4.hinet.net> wrote:
>
> Chris Angelico ? 2023?1?24? ?????5:00:27 [UTC+8] ??????
> > On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <c...@cskk.id.au> wrote:
> > >
> > > But for Jach Feng: the "--" is really expected as something the user
> > > does when they invoke your programme, _explicitly_ saying that what
> > > follows from here is not an argument. So the user is expected to type:
> > >
> > > your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
> > >
> > > where there are -x and -y options, then end of options, then an
> > > argument, which would look like an option if there wasn't the "--"
> > > argument.
> > And if you DON'T expect the user to enter the "--", then why use
> > argparse? You can just check argv directly to get your arguments.
> >
> > This entire thread is a massive "how can I use X to do Y?" problem.
> >
> > ChrisA
> The '--' requirement makes its usage less instinctive, and handling argv directly makes me loss the benefit of using '-h':-)

if "-h" in sys.argv: usage()
else: do_stuff_with(sys.argv[1:])

What is argparse really doing for you?

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 23Jan2023 17:58, Jach Feng <jfong@ms4.hinet.net> wrote:
>>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
>usage: [-h] infix
>: error: unrecognized arguments: -4.3+5

This error doesn't look like "-4.3+5 looks like an option" but instead
"we don't expect any arguments after "infix".

Not personally a fan of argparse myself, but then I have my own
elaborate command line framework which generally uses getopt for the
option stuff.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
cameron...@gmail.com ? 2023?1?24? ?????2:05:33 [UTC+8] ??????
> On 23Jan2023 17:58, Jach Feng <jf...@ms4.hinet.net> wrote:
> >>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
> >usage: [-h] infix
> >: error: unrecognized arguments: -4.3+5
> This error doesn't look like "-4.3+5 looks like an option" but instead
> "we don't expect any arguments after "infix".
>
> Not personally a fan of argparse myself, but then I have my own
> elaborate command line framework which generally uses getopt for the
> option stuff.
>
> Cheers,
> Cameron Simpson <c...@cskk.id.au>
Hmm, good to you. During experiments in these days, I had found argparse shows some strange/unstable behaviors in dealing with the leading '-' situation.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Stop please


Sent from Yahoo Mail for iPhone


On Tuesday, January 24, 2023, 1:05 AM, Cameron Simpson <cs@cskk.id.au> wrote:

On 23Jan2023 17:58, Jach Feng <jfong@ms4.hinet.net> wrote:
>>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
>usage: [-h] infix
>: error: unrecognized arguments: -4.3+5

This error doesn't look like "-4.3+5 looks like an option" but instead
"we don't expect any arguments after "infix".

Not personally a fan of argparse myself, but then I have my own
elaborate command line framework which generally uses getopt for the
option stuff.

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



--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/23/2023 9:12 PM, Chris Angelico wrote:
> On Tue, 24 Jan 2023 at 13:09, Jach Feng <jfong@ms4.hinet.net> wrote:
>>
>> Chris Angelico ? 2023?1?24? ?????5:00:27 [UTC+8] ??????
>>> On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <c...@cskk.id.au> wrote:
>>>>
>>>> But for Jach Feng: the "--" is really expected as something the user
>>>> does when they invoke your programme, _explicitly_ saying that what
>>>> follows from here is not an argument. So the user is expected to type:
>>>>
>>>> your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
>>>>
>>>> where there are -x and -y options, then end of options, then an
>>>> argument, which would look like an option if there wasn't the "--"
>>>> argument.
>>> And if you DON'T expect the user to enter the "--", then why use
>>> argparse? You can just check argv directly to get your arguments.
>>>
>>> This entire thread is a massive "how can I use X to do Y?" problem.
>>>
>>> ChrisA
>> The '--' requirement makes its usage less instinctive, and handling argv directly makes me loss the benefit of using '-h':-)
>
> if "-h" in sys.argv: usage()
> else: do_stuff_with(sys.argv[1:])
>
> What is argparse really doing for you?

I second this. "if '-h' in sys.argv:" is usually what I do.

Alternatively, you could use "--arg=" syntax and place your string
"-4^2+5.3*abs(-2-1)/2" its right-hand side":

infix2postfix [options] "--infix=-4^2+5.3*abs(-2-1)/2"

This shouldn't be too hard for a user to work with. You could scan the
argument list for the presence of "--infix=" and display the help
message if it isn't there.

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Can you stop please


Sent from Yahoo Mail for iPhone


On Tuesday, January 24, 2023, 10:12 AM, Thomas Passin <list1@tompassin.net> wrote:

On 1/23/2023 9:12 PM, Chris Angelico wrote:
> On Tue, 24 Jan 2023 at 13:09, Jach Feng <jfong@ms4.hinet.net> wrote:
>>
>> Chris Angelico ? 2023?1?24? ?????5:00:27 [UTC+8] ??????
>>> On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <c...@cskk.id.au> wrote:
>>>>
>>>> But for Jach Feng: the "--" is really expected as something the user
>>>> does when they invoke your programme, _explicitly_ saying that what
>>>> follows from here is not an argument. So the user is expected to type:
>>>>
>>>> your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
>>>>
>>>> where there are -x and -y options, then end of options, then an
>>>> argument, which would look like an option if there wasn't the "--"
>>>> argument.
>>> And if you DON'T expect the user to enter the "--", then why use
>>> argparse? You can just check argv directly to get your arguments.
>>>
>>> This entire thread is a massive "how can I use X to do Y?" problem.
>>>
>>> ChrisA
>> The '--' requirement makes its usage less instinctive, and handling argv directly makes me loss the benefit of using '-h':-)
>
> if "-h" in sys.argv: usage()
> else: do_stuff_with(sys.argv[1:])
>
> What is argparse really doing for you?

I second this.  "if '-h' in sys.argv:"  is usually what I do.

Alternatively, you could use "--arg=" syntax and place your string
"-4^2+5.3*abs(-2-1)/2" its right-hand side":

infix2postfix [options] "--infix=-4^2+5.3*abs(-2-1)/2"

This shouldn't be too hard for a user to work with.  You could scan the
argument list for the presence of "--infix=" and display the help
message if it isn't there.

--
https://mail.python.org/mailman/listinfo/python-list



--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/24/2023 10:13 AM, Mike Baskin wrote:
> Can you stop please

It's way past time, isn't it!

> Sent from Yahoo Mail for iPhone <https://overview.mail.yahoo.com/?.src=iOS>
>
> On Tuesday, January 24, 2023, 10:12 AM, Thomas Passin
> <list1@tompassin.net> wrote:
>
> On 1/23/2023 9:12 PM, Chris Angelico wrote:
> > On Tue, 24 Jan 2023 at 13:09, Jach Feng <jfong@ms4.hinet.net
> <mailto:jfong@ms4.hinet.net>> wrote:
> >>
> >> Chris Angelico ? 2023?1?24? ?????5:00:27 [UTC+8] ???
> ???
> >>> On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <c...@cskk.id.au
> <mailto:c...@cskk.id.au>> wrote:
> >>>>
> >>>> But for Jach Feng: the "--" is really expected as something
> the user
> >>>> does when they invoke your programme, _explicitly_ saying that
> what
> >>>> follows from here is not an argument. So the user is expected
> to type:
> >>>>
> >>>> your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
> >>>>
> >>>> where there are -x and -y options, then end of options, then an
> >>>> argument, which would look like an option if there wasn't the "--"
> >>>> argument.
> >>> And if you DON'T expect the user to enter the "--", then why use
> >>> argparse? You can just check argv directly to get your arguments.
> >>>
> >>> This entire thread is a massive "how can I use X to do Y?" problem.
> >>>
> >>> ChrisA
> >> The '--' requirement makes its usage less instinctive, and
> handling argv directly makes me loss the benefit of using '-h':-)
> >
> > if "-h" in sys.argv: usage()
> > else: do_stuff_with(sys.argv[1:])
> >
> > What is argparse really doing for you?
>
> I second this.  "if '-h' in sys.argv:"  is usually what I do.
>
> Alternatively, you could use "--arg=" syntax and place your string
> "-4^2+5.3*abs(-2-1)/2" its right-hand side":
>
> infix2postfix [options] "--infix=-4^2+5.3*abs(-2-1)/2"
>
> This shouldn't be too hard for a user to work with.  You could scan the
> argument list for the presence of "--infix=" and display the help
> message if it isn't there.
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
> <https://mail.python.org/mailman/listinfo/python-list>
>

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? WRONG TOOL [ In reply to ]
I understand we all want to be helpful and friendly, but it seems to me that helping someone use the wrong tool for the job isn$B!G(Bt really helpful in the long run.

argparse is for parsing command line arguments. It$B!G(Bs the wrong tool for this job.

As Chris Angelico already said: This entire thread is a massive "how can I use X to do Y?" problem.



From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Thomas Passin <list1@tompassin.net>
Date: Tuesday, January 24, 2023 at 10:23 AM
To: Mike Baskin <mikebaskin6538@yahoo.com>, python-list@python.org <python-list@python.org>
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On 1/24/2023 10:13 AM, Mike Baskin wrote:
> Can you stop please

It's way past time, isn't it!

> Sent from Yahoo Mail for iPhone <https://urldefense.com/v3/__https://overview.mail.yahoo.com/?.src=iOS__;!!Cn_UX_p3!g3YRQIW4wminyTVpjV9kATW-QRZ1YhvDi82oJvatyhNe_OABSPTU9c8KIOlztBNofs690OPwUdIyHt-2PcA$ >
>
> On Tuesday, January 24, 2023, 10:12 AM, Thomas Passin
> <list1@tompassin.net> wrote:
>
> On 1/23/2023 9:12 PM, Chris Angelico wrote:
> > On Tue, 24 Jan 2023 at 13:09, Jach Feng <jfong@ms4.hinet.net
> <mailto:jfong@ms4.hinet.net>> wrote:
> >>
> >> Chris Angelico $B:_(B 2023$BG/(B1$B7n(B24$BF|(B $B@14|Fs@6Zo(B5:00:27 [UTC+8] $BE*?.Cf(B
> $BUmF;!'(B
> >>> On Tue, 24 Jan 2023 at 07:47, Cameron Simpson <c...@cskk.id.au
> <mailto:c...@cskk.id.au>> wrote:
> >>>>
> >>>> But for Jach Feng: the "--" is really expected as something
> the user
> >>>> does when they invoke your programme, _explicitly_ saying that
> what
> >>>> follows from here is not an argument. So the user is expected
> to type:
> >>>>
> >>>> your_script -x -y -- "-4^2+5.3*abs(-2-1)/2"
> >>>>
> >>>> where there are -x and -y options, then end of options, then an
> >>>> argument, which would look like an option if there wasn't the "--"
> >>>> argument.
> >>> And if you DON'T expect the user to enter the "--", then why use
> >>> argparse? You can just check argv directly to get your arguments.
> >>>
> >>> This entire thread is a massive "how can I use X to do Y?" problem.
> >>>
> >>> ChrisA
> >> The '--' requirement makes its usage less instinctive, and
> handling argv directly makes me loss the benefit of using '-h':-)
> >
> > if "-h" in sys.argv: usage()
> > else: do_stuff_with(sys.argv[1:])
> >
> > What is argparse really doing for you?
>
> I second this. "if '-h' in sys.argv:" is usually what I do.
>
> Alternatively, you could use "--arg=" syntax and place your string
> "-4^2+5.3*abs(-2-1)/2" its right-hand side":
>
> infix2postfix [options] "--infix=-4^2+5.3*abs(-2-1)/2"
>
> This shouldn't be too hard for a user to work with. You could scan the
> argument list for the presence of "--infix=" and display the help
> message if it isn't there.
>
>
> --
> https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!g3YRQIW4wminyTVpjV9kATW-QRZ1YhvDi82oJvatyhNe_OABSPTU9c8KIOlztBNofs690OPwUdIykR5ILj4$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!g3YRQIW4wminyTVpjV9kATW-QRZ1YhvDi82oJvatyhNe_OABSPTU9c8KIOlztBNofs690OPwUdIykR5ILj4$>
> <https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!g3YRQIW4wminyTVpjV9kATW-QRZ1YhvDi82oJvatyhNe_OABSPTU9c8KIOlztBNofs690OPwUdIykR5ILj4$ >
>

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!g3YRQIW4wminyTVpjV9kATW-QRZ1YhvDi82oJvatyhNe_OABSPTU9c8KIOlztBNofs690OPwUdIykR5ILj4$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!g3YRQIW4wminyTVpjV9kATW-QRZ1YhvDi82oJvatyhNe_OABSPTU9c8KIOlztBNofs690OPwUdIykR5ILj4$>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/23/23 18:58, Jach Feng wrote:
> More pathonic, but don't work. The '--' must be at index 1:-)

I'm very confused. Why are you even using argparse, since if you put --
at index 1 then argparse wont't do any argument parsing at all. If all
you want is the expression on the command line, just access it directly.
If it's spread out with spaces, you can do something like this to put
it back together:

expression = " ".join(sys.argv[1:]

Otherwise the standard unix way of doing this is to require the user to
either provide the -- himself, or put the expression in quotes so it's
one unit.



--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Tue, 24 Jan 2023 15:13:33 +0000 (UTC), Mike Baskin
<mikebaskin6538@yahoo.com> declaimed the following:

>Can you stop please
>

Stop what?

You appear to be subscribed to the Python mailing list -- as such you
WILL receive all traffic that appears on that list. There is nothing we can
do. It is not a personal "you post, and only direct replies to you show
up".

BTW: the mailing list is gatewayed to newsgroup comp.lang.python...




--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
--
https://mail.python.org/mailman/listinfo/python-list
RE: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
If I understood the issue, the problem is the unary minus at the start of the expression.

So if you know the expression is in that argument, would it make sense to pad it in one of many ways that are otherwise harmless?

Could you put parens on both sides of "-4^2+5.3*abs(-2-1)/2":

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

Or perhaps place a zero in front as in the awkward case where it begins with a minus sign:

"0 -4^2+5.3*abs(-2-1)/2"

Some people suggest you ask the user to modify what they type in and such changes may work. Your program could also potentially diddle with argv and recognize it albeit as you allow calling a function like abs() I can easily imagine a potentially valid looking "-abs(...)..." that could look like -a followed by something.

I see a deeper issue with interactions at the command shell level if parts of the arithmetic expression are evaluated or changed before python is even invoked.

Then again, I may be misunderstanding the issue.



-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of Jach Feng
Sent: Tuesday, January 24, 2023 2:21 AM
To: python-list@python.org
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

cameron...@gmail.com ? 2023?1?24? ?????2:05:33 [UTC+8] ??????
> On 23Jan2023 17:58, Jach Feng <jf...@ms4.hinet.net> wrote:
> >>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
> >usage: [-h] infix
> >: error: unrecognized arguments: -4.3+5
> This error doesn't look like "-4.3+5 looks like an option" but instead
> "we don't expect any arguments after "infix".
>
> Not personally a fan of argparse myself, but then I have my own
> elaborate command line framework which generally uses getopt for the
> option stuff.
>
> Cheers,
> Cameron Simpson <c...@cskk.id.au>
Hmm, good to you. During experiments in these days, I had found argparse shows some strange/unstable behaviors in dealing with the leading '-' situation.
--
https://mail.python.org/mailman/listinfo/python-list

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Michael Torrie ? 2023?1?25? ?????3:05:44 [UTC+8] ??????
> On 1/23/23 18:58, Jach Feng wrote:
> > More pathonic, but don't work. The '--' must be at index 1:-)
> I'm very confused. Why are you even using argparse, since if you put --
> at index 1 then argparse wont't do any argument parsing at all. If all
> you want is the expression on the command line, just access it directly.
> If it's spread out with spaces, you can do something like this to put
> it back together:
>
> expression = " ".join(sys.argv[1:]
>
> Otherwise the standard unix way of doing this is to require the user to
> either provide the -- himself, or put the expression in quotes so it's
> one unit.
Maybe a condition is required before the modification,
if len(sys.argv) > 1 and not '-h' in sys.argv:
sys.argv.insert(1, '--')
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
avi.e...@gmail.com ? 2023?1?25? ?????6:39:13 [UTC+8] ??????
> If I understood the issue, the problem is the unary minus at the start of the expression.
>
> So if you know the expression is in that argument, would it make sense to pad it in one of many ways that are otherwise harmless?
>
> Could you put parens on both sides of "-4^2+5.3*abs(-2-1)/2":
>
> "(-4^2+5.3*abs(-2-1)/2)"
>
> Or perhaps place a zero in front as in the awkward case where it begins with a minus sign:
>
> "0 -4^2+5.3*abs(-2-1)/2"
>
> Some people suggest you ask the user to modify what they type in and such changes may work. Your program could also potentially diddle with argv and recognize it albeit as you allow calling a function like abs() I can easily imagine a potentially valid looking "-abs(...)..." that could look like -a followed by something.
>
> I see a deeper issue with interactions at the command shell level if parts of the arithmetic expression are evaluated or changed before python is even invoked.
>
> Then again, I may be misunderstanding the issue.
> -----Original Message-----
> From: Python-list <python-list-bounces+avi.e.gross=gmai...@python.org> On Behalf Of Jach Feng
> Sent: Tuesday, January 24, 2023 2:21 AM
> To: pytho...@python.org
> Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
> cameron...@gmail.com ? 2023?1?24? ?????2:05:33 [UTC+8] ??????
> > On 23Jan2023 17:58, Jach Feng <jf...@ms4.hinet.net> wrote:
> > >>>> parser.parse_args(['--', 'infix2postfix.py', '-4.3+5'])
> > >usage: [-h] infix
> > >: error: unrecognized arguments: -4.3+5
> > This error doesn't look like "-4.3+5 looks like an option" but instead
> > "we don't expect any arguments after "infix".
> >
> > Not personally a fan of argparse myself, but then I have my own
> > elaborate command line framework which generally uses getopt for the
> > option stuff.
> >
> > Cheers,
> > Cameron Simpson <c...@cskk.id.au>
> Hmm, good to you. During experiments in these days, I had found argparse shows some strange/unstable behaviors in dealing with the leading '-' situation.
> --
> https://mail.python.org/mailman/listinfo/python-list
The user may not know any unix idiom, or even don't know Python. Ask them to add extra characters in their equations to avoid the argparse conflict is strange to me.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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:-)
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Wed, 25 Jan 2023 at 14:42, Jach Feng <jfong@ms4.hinet.net> wrote:
> 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="....")
>

You're still not really using argparse as an argument parser. Why not
just do your own -h checking? Stop trying to use argparse for what
it's not designed for, and then wondering why it isn't doing what you
expect it to magically know.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Chris Angelico ? 2023?1?25? ?????1:16:25 [UTC+8] ??????
> On Wed, 25 Jan 2023 at 14:42, Jach Feng <jf...@ms4.hinet.net> wrote:
> > 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="....")
> >
> You're still not really using argparse as an argument parser. Why not
> just do your own -h checking? Stop trying to use argparse for what
> it's not designed for, and then wondering why it isn't doing what you
> expect it to magically know.
>
> ChrisA
I just don't get what you mean?

> You're still not really using argparse as an argument parser. Why not just do your own -h checking?

Is a math equation not qualified as a command line "argument"? What criteria do you use when judging the quality of an "argument"?

> Stop trying to use argparse for what it's not designed for,

Even the author considers a positional argument begin with '-' is a legal argument. Below is a quote from its manual.

"If you have positional arguments that must begin with - and don’t look like negative numbers, you can insert the pseudo-argument '--' which tells parse_args() that everything after that is a positional argument"

> and then wondering why it isn't doing what you expect it to magically know."

I don't expect magic, I expect the consistency of a parser.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 25Jan2023 16:15, Chris Angelico <rosuav@gmail.com> wrote:
>On Wed, 25 Jan 2023 at 14:42, Jach Feng <jfong@ms4.hinet.net> wrote:
>> I was happy working with argparse during implement my script. To save the typing, I used a default equation for testing.

Sure, but what benefit was it bringing you? Just the usage (help)
message? Did you have many options to handle?

>> 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="....")

If this was the whole thing, I don't see what argparse was doing for you
which was better than just handling the arguments yourself - there's
only one after all.

>You're still not really using argparse as an argument parser. Why not
>just do your own -h checking? Stop trying to use argparse for what
>it's not designed for, and then wondering why it isn't doing what you
>expect it to magically know.

I'm with Chris here.

As someone who pretty well _never_ uses argparse, and occasionally uses
getopt, I'd do something like this:

usage = '''Usage: infix
Parse the argument infix as an expression, print the result.'''

badopts = False
cmd = argv.pop(0)
if not argv:
print(f'{cmd}: missing infix argument', file=sys.stderr)
badopts = True
else:
infix = argv.pop(0)
if infix in ('-h', '--help'):
print(usage)
exit(0)
if argv:
print(f'{cmd}: extra arguments after infix: {argv!r}', file=sys.stderr)
badopts = True
if badopts:
print(usage, file=sys.stderr)
exit(2)
... work with infix as desired ...

This:
- avoids trying to shoehorn argparse into behaving in a way it was not
designed for
- avoids users needing to know the standard UNIX/POSIX "--" idiom for
marking off the end of options
- supports a -h or --help leading option

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Thu, 26 Jan 2023 at 04:25, Jach Feng <jfong@ms4.hinet.net> wrote:
>
> Chris Angelico ? 2023?1?25? ?????1:16:25 [UTC+8] ??????
> > On Wed, 25 Jan 2023 at 14:42, Jach Feng <jf...@ms4.hinet.net> wrote:
> > > 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="....")
> > >
> > You're still not really using argparse as an argument parser. Why not
> > just do your own -h checking? Stop trying to use argparse for what
> > it's not designed for, and then wondering why it isn't doing what you
> > expect it to magically know.
> >
> > ChrisA
> I just don't get what you mean?
>
> > You're still not really using argparse as an argument parser. Why not just do your own -h checking?
>
> Is a math equation not qualified as a command line "argument"? What criteria do you use when judging the quality of an "argument"?
>

Print out sys.argv and then figure out whether you need an argument
*parser* to *parse* your arguments. From what I'm seeing, you don't.
You just need the arguments.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Use a different prefix character

parser = argparse.ArgumentParser(prefix_chars='%')
parser.add_argument('expression')

args = parser.parse_args()
print(args.expression)

argparser is for allowing multiple command line options to be passed, providing default, controlling the number of arguments and the like.


From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Jach Feng <jfong@ms4.hinet.net>
Date: Wednesday, January 25, 2023 at 12:25 PM
To: python-list@python.org <python-list@python.org>
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

Chris Angelico $B:_(B 2023$BG/(B1$B7n(B25$BF|(B $B@14|;02<8a(B1:16:25 [UTC+8] $BE*?.CfUmF;!'(B
> On Wed, 25 Jan 2023 at 14:42, Jach Feng <jf...@ms4.hinet.net> wrote:
> > 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="....")
> >
> You're still not really using argparse as an argument parser. Why not
> just do your own -h checking? Stop trying to use argparse for what
> it's not designed for, and then wondering why it isn't doing what you
> expect it to magically know.
>
> ChrisA
I just don't get what you mean?

> You're still not really using argparse as an argument parser. Why not just do your own -h checking?

Is a math equation not qualified as a command line "argument"? What criteria do you use when judging the quality of an "argument"?

> Stop trying to use argparse for what it's not designed for,

Even the author considers a positional argument begin with '-' is a legal argument. Below is a quote from its manual.

"If you have positional arguments that must begin with - and don$B!G(Bt look like negative numbers, you can insert the pseudo-argument '--' which tells parse_args() that everything after that is a positional argument"

> and then wondering why it isn't doing what you expect it to magically know."

I don't expect magic, I expect the consistency of a parser.
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jfetVCL_U0v2RwXvkQWkim9VOYbZSJsWxRjWVlhpCDNHLoBWGyPJKGC_vh1Hwkrm3AzcX2KNEOUFKNNBx0tG$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jfetVCL_U0v2RwXvkQWkim9VOYbZSJsWxRjWVlhpCDNHLoBWGyPJKGC_vh1Hwkrm3AzcX2KNEOUFKNNBx0tG$>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Thu, 26 Jan 2023 at 04:24, Jach Feng <jfong@ms4.hinet.net> wrote:
> Chris Angelico ? 2023?1?25? ?????1:16:25 [UTC+8] ??????
> > On Wed, 25 Jan 2023 at 14:42, Jach Feng <jf...@ms4.hinet.net> wrote:

> > You're still not really using argparse as an argument parser. Why not
> > just do your own -h checking? Stop trying to use argparse for what
> > it's not designed for, and then wondering why it isn't doing what you
> > expect it to magically know.

> I just don't get what you mean?

Hi, I am writing because there seems to be a communication
problem here, not a programming problem. The thread is long
and seems to be making no progress.

You seem like a traveller who is lost and keeps looking at the
map, but they have the wrong map for where they are.

You seem to be not understanding the purpose of argparse.

In this thread, you have not mentioned any reason that requires
the use of argparse.

argparse is intended to help when your program accepts
>>> more than one kind of argument <<<
and then uses those different kinds of argument
>>> for different purposes <<<.

The programmer can handle that situation without argparse.
But argparse makes it easier.

In this thread, you have not described your program as accepting
different kinds of arguments. Therefore the people replying to you
are telling you that you do not need it.

You seem to be not listening to that, and you have not explained why,
you seem to just keep ignoring what people are telling you.

If you disagree with this, then a way forward is for you to think harder
about what benefits you are getting in your program by using argparse,
and >>> explain those benefits clearly to your readers here <<<.

An alternative approach would be for you to remove argparse from
your program, and try to write your program without it. And
then ask here about any difficulties that you have with doing that,
and I imagine people will be glad to help you.

All of the replies you have received so far are trying to help you,
even if you don't feel that. Good luck.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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 appreciate every comment/suggestion in this thread even sometimes I may not fully understand what they mean. To me, argparse has been just a tool which I can use in a CLI app. I use it as long as the situation allows, even it's as simple as only one positional argument is needed. Now I understand some oppose this idea and saying that you shouldn't use a kitchen knife to cut a cake:-)
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Thu, 26 Jan 2023 at 14:13, Jach Feng <jfong@ms4.hinet.net> wrote:
> Now I understand some oppose this idea and saying that you shouldn't use a kitchen knife to cut a cake:-)

You shouldn't use a chainsaw to cut a cake, and then ask us why
cake-cutting is so noisy.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/24/23 23:28, Jach Feng wrote:
> Chris Angelico ? 2023?1?25? ?????1:16:25 [UTC+8] ??????
>> On Wed, 25 Jan 2023 at 14:42, Jach Feng <jf...@ms4.hinet.net> wrote:
>>> 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="....")
>>>
>> You're still not really using argparse as an argument parser. Why not
>> just do your own -h checking? Stop trying to use argparse for what
>> it's not designed for, and then wondering why it isn't doing what you
>> expect it to magically know.
>>
>> ChrisA
> I just don't get what you mean?
>
>> You're still not really using argparse as an argument parser. Why not just do your own -h checking?
>
> Is a math equation not qualified as a command line "argument"? What criteria do you use when judging the quality of an "argument"?

The ancient UNIX concept, later codified in the POSIX international
standard, is that if an argument begins with a '-' it specifies an
option. The three standard library CLI argument parsers (getopt,
optparse and argparse) all follow this convention. You're feeding it
something that they will conclude is an option, but you have given
argparse no information how to deal with such an option. The advice
you've been given is: this is built in behavior. You don't want that
behavior. Either "fool" the module somehow (quoting with leading spaces,
use the special option identifier of a bare double dash indicating "end
of options", etc.) - or just don't use a module that behaves in a way
you don't like.



--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 1/25/23 19:50, Jach Feng wrote:
> To me, argparse has been just a tool which I can use in a CLI app.

argparse is just a tool for dealing with command-line *flags*, which are
common in command-line tools. argparse interprets the command line as a
bunch of flags because that's what it's designed to do. I find it
baffling that you expect some other behavior from argparse.

You don't need or want argparse in this situation. sys.argv has
everything you need in it. Use it directly!

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Jach Feng wrote:
> 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.

If you can use it in the way you want, that's great. I thought you were
asking here because you *couldn't* use it the way you want.

You're writing a command-line application. Your users are either
already familiar with the conventions of command-line applications, or
they'll soon need to be.

If your application supports options beginning with a "-" (which is what
argparse gives you, even if only the default "-h" and "--help" options
are actually valid), and you also need to be able to pass positional
arguments which begin with a "-", you need some way for the user to
indicate whether any particular argument is an option or positional.
Using "--" to indicate that all subsequent arguments are positional, not
options, is a common convention.

Some of your users might already be familiar with that convention from
other command-line tools. By using the same convention, you'd be making
it easier for them to use yours. Others might not already be familiar
with the convention, but by being consistent with other tools you'd
still be helping them when they eventually do come across it elsewhere.
You can always include an explanation of using "--" in your usage output
or other documentation.

Apart from dealing with how to pass an argument beginning with "-", your
users will also likely have to deal with the features of whichever shell
they're using, which you have no control over. For example, it's quite
common to need to enclose an argument in quotes if it contains spaces.
It may also be necessary to use quotes if certain special characters are
used, such as "*", "?" or "$" (perhaps "%" on Windows).

> 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()

Personally, I do quite often use argparse even for simple cases, partly
because it produces nice usage details, and deals with wrapping the
output to whatever width the console is. But I work with it rather than
against it, and accept that a "--" is needed if a positional argument
starts with a "-".

I notice you explain the need to enclose the equation in quotes if it
contains spaces. That's not even a feature of your application, but of
the shell used to call it. So why so much objection to explaining the
need for "--"?

Depending on the shell, there are other cases where quoting might be
needed, e.g. if the equation includes a "*" or "?" and happens to look
like a pattern matching files in the current directory (most shells I've
used pass the pattern unchanged if it doesn't match any files). In
bash, if a "$" is used I'd need to enclose that in 'single quotes'
(can't even use "double quotes" for that one). You can't really expect
to document all that sort of thing, because it depends on which shell
the user happens to run your application from - you just have to trust
the user to know or learn how to use their shell.

--
Mark.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Mark Bourne ? 2023?1?28? ?????10:00:01 [UTC+8] ??????
> Jach Feng wrote:
> > 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.
> If you can use it in the way you want, that's great. I thought you were
> asking here because you *couldn't* use it the way you want.
>
> You're writing a command-line application. Your users are either
> already familiar with the conventions of command-line applications, or
> they'll soon need to be.
>
> If your application supports options beginning with a "-" (which is what
> argparse gives you, even if only the default "-h" and "--help" options
> are actually valid), and you also need to be able to pass positional
> arguments which begin with a "-", you need some way for the user to
> indicate whether any particular argument is an option or positional.
> Using "--" to indicate that all subsequent arguments are positional, not
> options, is a common convention.
>
> Some of your users might already be familiar with that convention from
> other command-line tools. By using the same convention, you'd be making
> it easier for them to use yours. Others might not already be familiar
> with the convention, but by being consistent with other tools you'd
> still be helping them when they eventually do come across it elsewhere.
> You can always include an explanation of using "--" in your usage output
> or other documentation.
>
> Apart from dealing with how to pass an argument beginning with "-", your
> users will also likely have to deal with the features of whichever shell
> they're using, which you have no control over. For example, it's quite
> common to need to enclose an argument in quotes if it contains spaces.
> It may also be necessary to use quotes if certain special characters are
> used, such as "*", "?" or "$" (perhaps "%" on Windows).
> > 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()
> Personally, I do quite often use argparse even for simple cases, partly
> because it produces nice usage details, and deals with wrapping the
> output to whatever width the console is. But I work with it rather than
> against it, and accept that a "--" is needed if a positional argument
> starts with a "-".
>
> I notice you explain the need to enclose the equation in quotes if it
> contains spaces. That's not even a feature of your application, but of
> the shell used to call it. So why so much objection to explaining the
> need for "--"?
>
> Depending on the shell, there are other cases where quoting might be
> needed, e.g. if the equation includes a "*" or "?" and happens to look
> like a pattern matching files in the current directory (most shells I've
> used pass the pattern unchanged if it doesn't match any files). In
> bash, if a "$" is used I'd need to enclose that in 'single quotes'
> (can't even use "double quotes" for that one). You can't really expect
> to document all that sort of thing, because it depends on which shell
> the user happens to run your application from - you just have to trust
> the user to know or learn how to use their shell.
>
> --
> Mark.
Thank you for detail explanation of the role the shell is involved in this problem. I'm very appreciated!

It seems that a CLI app may become very complex when dealing with different kind of shell, and may not be possible to solve its problem. But the good thing in my app is that I need only to handle math equation:-)

> So why so much objection to explaining the need for "--"?
Because of using " to enclose a space separated string is a common convention, and adding a "--" is not:-)

--Jach
--
https://mail.python.org/mailman/listinfo/python-list
RE: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Jack,

I get uneasy when someone thinks a jackhammer is a handy dandy tool for pushing in a thumbtack that is sitting on my expensive table.

I agree it is quite easy to grab some code that does lot of things and also does something truly minor, and use it for that purpose. Sometimes the cost is that it is far slower. I mean if I want to print the smaller of variables alpha and beta containing integers, I could combine them in something like a list or array and call a nifty sort() function someone wrote that takes a function argument that lets you compare whatever is needed and it likely will work. You get back the result and print the first item in the sorted output or maybe the last. You could have used a simpler function like min(alpha, beta) and skipped making a list of them. Heck, you could have used a fairly simple if statement.

But if you searched the internet and found a function that takes any number of data items and performs many statistical tests on it tat start with things like mean, median and mode and continues to calculate standard deviation, and skew and standard error and also the min/max/range. Sounds good. It returns some structure/object and you dig into it and find the minimum and you are done!

It sounds like the jackhammer approach to me.

In your case, there is indeed nothing wrong with using the function to help parse the command line arguments and you are being told that it generally works EXCEPT when it is documented NOT TO WORK. It was designed to deal with UNIX conventions so you could call a program with a mix of optional flags and then optional arguments such as filenames or anything else or ALMOST anything else. The early design allowed something like to list files using:

ls - la *.c

or

ls - l -a *.c

Or many more variations that can include newer ways that use longer options. People ran into the problem of having some options that included a word following them that is to be parsed as part of that option and other enhancements. The minus sign or hyphen was chosen and is not trivial to change. So the idea was to add a flag with two minus signs that has no meaning other than to say that anything after that is to be somewhat ignored as not being a flag. Thus it is safe for any further arguments to start with a minus sign.

How does that line up with some of the advice you got?

One idea was to have your users told they should add a " -- " (without quotes) before the formula you want to evaluate. Another was asking if you had a more complex command line with many options that needed a swiss army knife approach. If not, since you have formulas starting with a minus sign that may be used, consider NOT using a tool you admit you did not understand.

And since python like many languages provides you with a data structure that already holds the info you need, use the thumbtack approach or find or write a different library function that extracts what you need in an environment where it is NOT looking for things with a minus sign.

You know when you go to a doctor and ask why a part of your skin is bleeding and so on, and you admit you keep scratching yourself, rather than suggesting complex surgeries or putting your hands in a cast to keep you from scratching, they may first try telling you to NOT DO THAT and let it heal.

Do note a final point. There is nothing magical about using a minus sign in UNIX and they could have insisted say that command line arguments be placed in square brackets or some other method to identify them. It seemed harmless to use a minus sign at the time. But the programs they includes starting using so many allowed tweaks of many kinds, that it got really hard to parse what was being asked and thus several libraries of functions have been built that manage all that. Your problem is far from unique as any program trying to deal with an argument for a filename that begins with a minus sign will have a similar problem. Programs like grep often take an argument that is a regular expression or other utilities take a "program" that also may for whatever reason start with a minus sign.

Some people ask a question and you have asked many here, and got answers. Usually you accept what people tell you better. I am trying to say that the issue is not whether you are using the wrong tool in general. It is that NOW that you know there is sometimes a problem, you resist understanding it was never designed to do what you want.


-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of Jach Feng
Sent: Saturday, January 28, 2023 12:04 AM
To: python-list@python.org
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

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

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On Sun, 29 Jan 2023 at 14:29, Jach Feng <jfong@ms4.hinet.net> wrote:
> Thank you for detail explanation of the role the shell is involved in this problem. I'm very appreciated!
>
> It seems that a CLI app may become very complex when dealing with different kind of shell, and may not be possible to solve its problem. But the good thing in my app is that I need only to handle math equation:-)
>
> > So why so much objection to explaining the need for "--"?
> Because of using " to enclose a space separated string is a common convention, and adding a "--" is not:-)

Double hyphen is incredibly common.

On most Unix shells, double quotes are just one way of marking that a
space should be included in an argument rather than separating (others
include single quotes, escaping the space with a backslash, and
changing the field separator). Of course, everything is conventions,
not requirements, but it's generally better to let the person's shell
define the argument splitting; that way, if your script is called from
another process, it's dead easy to control the splitting yourself
(just pass an array/list of arguments to the subprocess spawner).

Maybe you come from Windows, where there are fewer conventions and
less shell parsing, but argparse follows Unix conventions, so if you
don't want Unix conventions, don't use argparse. Just read sys.argv
directly.

ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 28Jan2023 18:55, Jach Feng <jfong@ms4.hinet.net> wrote:
>Mark Bourne ? 2023?1?28? ?????10:00:01 [UTC+8] ??????
>> I notice you explain the need to enclose the equation in quotes if it
>> contains spaces. That's not even a feature of your application, but of
>> the shell used to call it. So why so much objection to explaining the
>> need for "--"?
>>
>> Depending on the shell, there are other cases where quoting might be
>> needed, e.g. if the equation includes a "*" or "?" and happens to look
>> like a pattern matching files in the current directory (most shells I've
>> used pass the pattern unchanged if it doesn't match any files). In
>> bash, if a "$" is used I'd need to enclose that in 'single quotes'
>> (can't even use "double quotes" for that one). You can't really expect
>> to document all that sort of thing, because it depends on which shell
>> the user happens to run your application from - you just have to trust
>> the user to know or learn how to use their shell.
>
>Thank you for detail explanation of the role the shell is involved in this problem. I'm very appreciated!

The shell has basicly _nothing_ to do with your problems. By the time
you've got sys.argv in your Python programme you will have no idea
whether quotes were used with an argument. (UNIX/POSIX, not Windows,
where things are ... more complex.) This means you don't know if the use
typed:

-4.5

or

"-4.5"

You'll just get a string '4.5' in your Python programme both ways.

All the quotes in the shell do is delimit what things should be kept
together as a single argument versus several, or where variables should
be interpolated when computing arguments etc. It's just _shell_
punctuation and the invoked programme doesn't see it.

>It seems that a CLI app may become very complex when dealing with different kind of shell, and may not be possible to solve its problem.

It doesn't matter what shell is used. The just controls what punctuation
the end user may need to use to invoke your programme. You programme
doesn't need to care (and can't because it doesn't get the quotes etc,
only their result).

>> So why so much objection to explaining the need for "--"?
>Because of using " to enclose a space separated string is a common convention, and adding a "--" is not:-)

They're unrelated. As others have mentioned, "--" is _extremely_ common;
almost _all_ UNIX command like programmes which handle -* style options
honour the "--" convention. _argparse_ itself honours that convention,
as does getopt etc.

The "--" convention has nothing to do with the shell.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
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
OK, I take a quick try to use argv directly. I write the code in a way even get rid of the -h option.

import sys
if len(sys.argv) == 1:
....infix = " "
....print("Usage: a math equation must follow!")
else:
....infix = "".join(sys.argv[1:])

Simple enough, right? But unfortunately it didn't survive. The ^ symbol was lost!

e:\Works\Python>py infix2postfix.py
Usage: a math equation must follow!

e:\Works\Python>py infix2postfix.py -4^2 +5.3 * abs(-2-1)/2
-42 5.3 -2 1 - abs * 2 / +

Hmm...
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 2023-01-29 at 16:51:20 +1100,
Cameron Simpson <cs@cskk.id.au> wrote:

> They're unrelated. As others have mentioned, "--" is _extremely_ common;
> almost _all_ UNIX command like programmes which handle -* style options
> honour the "--" convention. _argparse_ itself honours that convention, as
> does getopt etc.

And why do UNIX programs behave this way?

Because POSIX says they should:

https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
--
https://mail.python.org/mailman/listinfo/python-list
RE: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Although today you could say POSIX is the reason for many things including
the use of "--" I hesitate to mention I and many others used that convention
long before as a standard part of many UNIX utilities. Like many other such
things, you build things first and by the time you standardize, ...


-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On
Behalf Of 2QdxY4RzWzUUiLuE@potatochowder.com
Sent: Sunday, January 29, 2023 7:12 AM
To: python-list@python.org
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string
argument?

On 2023-01-29 at 16:51:20 +1100,
Cameron Simpson <cs@cskk.id.au> wrote:

> They're unrelated. As others have mentioned, "--" is _extremely_
> common; almost _all_ UNIX command like programmes which handle -*
> style options honour the "--" convention. _argparse_ itself honours
> that convention, as does getopt etc.

And why do UNIX programs behave this way?

Because POSIX says they should:

https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
--
https://mail.python.org/mailman/listinfo/python-list

--
https://mail.python.org/mailman/listinfo/python-list
RE: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Cameron,

You are technically correct but perhaps off the mark.

Yes, a python program only sees what is handed to it by some shell if invoked a certain way.

The issue here is what you tell people using your program about what they need to type to get it to work. That means if their shell is going to make changes in what they typed, they need to know how to avoid unintended changes. As one example not mentioned, whitespace disappears if not somehow protected as in quotes.

What the OP is being told is that their Python program only controls what is fed to it. A user needs to know enough to avoid doing silly things like provide an unquoted string containing reserved symbols like a pipe symbol or odd things may happen and their program may not even be called.

So the documentation of how to use the program may need to spell some things out alongside suggesting use of "--" ...


-----Original Message-----
From: Python-list <python-list-bounces+avi.e.gross=gmail.com@python.org> On Behalf Of Cameron Simpson
Sent: Sunday, January 29, 2023 12:51 AM
To: python-list@python.org
Subject: Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

On 28Jan2023 18:55, Jach Feng <jfong@ms4.hinet.net> wrote:
>Mark Bourne ? 2023?1?28? ?????10:00:01 [UTC+8] ??????
>> I notice you explain the need to enclose the equation in quotes if it
>> contains spaces. That's not even a feature of your application, but
>> of the shell used to call it. So why so much objection to explaining
>> the need for "--"?
>>
>> Depending on the shell, there are other cases where quoting might be
>> needed, e.g. if the equation includes a "*" or "?" and happens to
>> look like a pattern matching files in the current directory (most
>> shells I've used pass the pattern unchanged if it doesn't match any
>> files). In bash, if a "$" is used I'd need to enclose that in 'single quotes'
>> (can't even use "double quotes" for that one). You can't really
>> expect to document all that sort of thing, because it depends on
>> which shell the user happens to run your application from - you just
>> have to trust the user to know or learn how to use their shell.
>
>Thank you for detail explanation of the role the shell is involved in this problem. I'm very appreciated!

The shell has basicly _nothing_ to do with your problems. By the time you've got sys.argv in your Python programme you will have no idea whether quotes were used with an argument. (UNIX/POSIX, not Windows, where things are ... more complex.) This means you don't know if the use
typed:

-4.5

or

"-4.5"

You'll just get a string '4.5' in your Python programme both ways.

All the quotes in the shell do is delimit what things should be kept together as a single argument versus several, or where variables should be interpolated when computing arguments etc. It's just _shell_ punctuation and the invoked programme doesn't see it.

>It seems that a CLI app may become very complex when dealing with different kind of shell, and may not be possible to solve its problem.

It doesn't matter what shell is used. The just controls what punctuation the end user may need to use to invoke your programme. You programme doesn't need to care (and can't because it doesn't get the quotes etc, only their result).

>> So why so much objection to explaining the need for "--"?
>Because of using " to enclose a space separated string is a common
>convention, and adding a "--" is not:-)

They're unrelated. As others have mentioned, "--" is _extremely_ common; almost _all_ UNIX command like programmes which handle -* style options honour the "--" convention. _argparse_ itself honours that convention, as does getopt etc.

The "--" convention has nothing to do with the shell.

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

--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 2023-01-29 07:59:21 -0500, avi.e.gross@gmail.com wrote:
> Although today you could say POSIX is the reason for many things including
> the use of "--" I hesitate to mention I and many others used that convention
> long before as a standard part of many UNIX utilities.

I somewhat doubt that you are remembering correctly. The POSIX standard
was published in 1988. I was starting to use Unix shortly before that
and I don't think there was really a common way to indicate the end of
the options. Some utilities used "-", some "--", some just stopped at
the first argument which didn't look like an option ...

The convergence to "--" happened later. My guess is that GNU getopt and
the popularity of the GNU utilities had a lot to do with it.

> Like many other such things, you build things first and by the time
> you standardize, ...

Right. But in this case lots of people were building different things
and then *one* of them was standardized. Truth to be told, I don't know
when that happened. It might have been in the original 1988 edition of
POSIX, but I don't think so. I think it was in a later (possibly much
later) edition, wennn "--" was already really common. But POSIX did lead
the way in some cases and it might have been the case here, too.

hp

--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | hjp@hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 2023-01-27 21:03:39 -0800, Jach Feng wrote:
> 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

I don't see what's new about that.

> which may make someone feel uneasy.

It seems that the person who feels most uneasy about it is yourself
because it doesn't work like you want it to.


> 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,

It would almost certainly be shorter and easier to understand,
especially since you are *also* handling sys.argv directly in your code
to prevent argparse to work as designed.

But since you are probably the only person who will have to read your
code in the future that's not our problem.

hp

--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | hjp@hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Jach Feng wrote:
> 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
> OK, I take a quick try to use argv directly. I write the code in a way even get rid of the -h option.
>
> import sys
> if len(sys.argv) == 1:
> ....infix = " "
> ....print("Usage: a math equation must follow!")
> else:
> ....infix = "".join(sys.argv[1:])
>
> Simple enough, right? But unfortunately it didn't survive. The ^ symbol was lost!
>
> e:\Works\Python>py infix2postfix.py
> Usage: a math equation must follow!
>
> e:\Works\Python>py infix2postfix.py -4^2 +5.3 * abs(-2-1)/2
> -42 5.3 -2 1 - abs * 2 / +
>
> Hmm...

I'm not certain, but I think that's a shell feature again. In Windows'
command prompt, "^" can be used at the end of a line to indicate that
the command continues on the next line. I'm not sure what happens if
it's in the middle of a line (and not on Windows to be able to check),
but it's quite possible that it just gets ignored.

Enclosing your argument in quotes might help. Again, this is a feature
of the shell, not your application, and other shells might behave
differently. You probably don't want to go down the line of trying to
document this kind of thing in your applications usage information,
because it won't work like that for someone using e.g. the bash shell
(which can be run on Windows).

--
Mark.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
Jach Feng wrote:
> Thank you for detail explanation of the role the shell is involved in this problem. I'm very appreciated!
>
> It seems that a CLI app may become very complex when dealing with different kind of shell, and may not be possible to solve its problem. But the good thing in my app is that I need only to handle math equation:-)

If you want to try to tell the user how to deal with their shell's
requirements for quoting arguments, regardless of which shell they might
be using, yes, that explanation would become very complicated. It
doesn't affect the rest of the implementation of the application though
- the user just needs to know how to use their shell to pass the
arguments they want into the application. That's really something they
should look up in their shell's documentation, rather than something
your application should attempt to document.

Since your application requires equations to be passed in, and they're
quite likely to include characters handled specially by the shell
(space, "*" and "^" have already come up in this thread, but there may
be others), it may be worth highlighting that, but directing the user to
consult the documentation for their shell rather than assuming a
particular shell and attempting to cover all its features and limitations.

>> So why so much objection to explaining the need for "--"?
> Because of using " to enclose a space separated string is a common convention, and adding a "--" is not:-)

If you don't consider use of "--" to be a common convention, that seems
even more reason to mention it in your application's documentation.

Telling the user to use quotes around an argument containing spaces is
nothing to do with your application, and might not even be applicable if
they use a different shell to call your application. In most shells
I've come across, there are also various other characters that need
special handling (either quoting or escaping) - but exactly which
characters again depends on the shell. Yet you seem quite happy to
document that one particular case in your usage information.

Using "--" is also a common convention (as I and others have mentioned),
although perhaps not as common in Windows (where it's more common to use
"/" rather than "-" for options anyway). But more to the point, it is a
feature that is implemented under your application's control (if you
don't want this feature, don't use argparse). Use of "--" is applicable
regardless of which shell your user calls it from, and other
applications might not use that convention even if called from the same
shell, so it seems *more* in scope for your application to document than
using quotes around spaces.

--
Mark.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
This thread has run its course and seems to now be generating more heat than light.

It is now closed (at least on the Python List side).

Thank you everyone for your participation and understanding.

--
~Ethan~
Moderator
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 29Jan2023 07:12, 2QdxY4RzWzUUiLuE@potatochowder.com <2QdxY4RzWzUUiLuE@potatochowder.com> wrote:
>On 2023-01-29 at 16:51:20 +1100,
>Cameron Simpson <cs@cskk.id.au> wrote:
>> They're unrelated. As others have mentioned, "--" is _extremely_
>> common;
>> almost _all_ UNIX command like programmes which handle -* style options
>> honour the "--" convention. _argparse_ itself honours that convention, as
>> does getopt etc.
>
>And why do UNIX programs behave this way?
>
>Because POSIX says they should:
>
> https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html

Aye, but POSIX says they should because POSIX formalises a lot of
existing practices so that people have a reference to let them _also_
use that practice in a consistent way.

I used to lurk on the POSIX discussion list, and the length of the
discussions around corner cases was quite wearing, even just to read.

Cheers,
Cameron Simpson <cs@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? [ In reply to ]
On 29Jan2023 08:10, avi.e.gross@gmail.com <avi.e.gross@gmail.com> wrote:
>You are technically correct but perhaps off the mark.
>
>Yes, a python program only sees what is handed to it by some shell if invoked a certain way.
>
>The issue here is what you tell people using your program about what they need to type to get it to work. That means if their shell is going to make changes in what they typed, they need to know how to avoid unintended changes. As one example not mentioned, whitespace disappears if not somehow protected as in quotes.

Hmm, there is that. But the OP needs clarity on what happens in a shell
and what happens in a programme once the shell has invoked it for a
user.

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