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

Cameron Simpson cs at cskk.id.au
Wed Jan 25 01:45:28 EST 2023


On 25Jan2023 16:15, Chris Angelico <rosuav at gmail.com> wrote:
>On Wed, 25 Jan 2023 at 14:42, Jach Feng <jfong at 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 at cskk.id.au>


More information about the Python-list mailing list