How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

Cameron Simpson cs at cskk.id.au
Sun Jan 29 00:51:20 EST 2023


On 28Jan2023 18:55, Jach Feng <jfong at 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 at cskk.id.au>


More information about the Python-list mailing list