-1

Currently I am writing the script that accepts space separated arguments like this

parser = argparse.ArgumentParser(description='foo 1.0')
parser.add_argument('-a', '--arch', help='specify the angle', nargs="+" choices=ch_list, required=True

I am passing either

+foo +bar +baz

or

-foo -bar -baz

or

foo bar baz

where foo bar baz are alphanum elements

What is the most elegant way of sorting arguments out?

Either all should have + sign or - sign or no sign at all, if arguments mix happened the script should throw the error and exit.

1 Answers1

0

1) You can't pass any of -foo, -baz, -bar as values. The hyphen will make ArgParse interpret it as an option flag and spew out an error.

2)

What is the most elegant way of sorting arguments out?

You can have

ch_list = ['foo', 'bar', 'baz', '+foo', '+bar', '+baz'] 

which would ensure nothing outside of that list is allowed, but it wouldn't prevent the user from entering a mix and match of the different formats say./program --arch foo +baz +bar.

To prevent that, you would need to validate the arguments yourself after parse_args().

  args = parser.parse_args()
  l = args.arch if args.arch is not None else []
  if len(l):
    has_plus = lambda x : x[0] == '+'
    first_has_plus = has_plus(l[0])
    for x in l:
      if first_has_plus ^ has_plus(x):
        print("INVALID")
        return
    print("PASSED")
Sami Farhat
  • 1,164
  • 8
  • 12