3

I'm doing a command line utility that can receive a parameter starting with a minus or plus, for instance, -gtest or +gtest the problem is that python3 don't accept this:

This is a minimal code that reproduce this problem: import argparse

if (__name__== "__main__"):
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--string', action='store',
                        help='String value')
    p = parser.parse_args()
    if p.string:
        print("pass value:", p.string)

I try to invoke it as:

./example.py -s -gtest
./example.py -s "-gtest"
./example.py -s \-gtest

And always get next error:

usage: example.py [-h] [-s STRING]
example.py: error: argument -s/--string: expected one argument

So, my question is how I can pass a argument starting with a minus using argparse

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Joan Esteban
  • 1,006
  • 12
  • 23

1 Answers1

2

You can run it with:

python example.py -s-gtest
python example.py -s+gtest

So simply not putting any space, nor escaping it in any special way.

Grzegorz Oledzki
  • 23,614
  • 16
  • 68
  • 106