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

Cameron Simpson cs at cskk.id.au
Mon Jan 23 15:31:45 EST 2023


On 23Jan2023 13:46, 2QdxY4RzWzUUiLuE at potatochowder.com <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
>On 2023-01-22 at 18:19:13 -0800,
>Jach Feng <jfong at 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 at cskk.id.au>


More information about the Python-list mailing list