Mailing List Archive

1 2 3  View All
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

1 2 3  View All