Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a parameter value starting with minus (-) using argparse [duplicate]

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

like image 476
Joan Esteban Avatar asked Oct 26 '25 10:10

Joan Esteban


1 Answers

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.

like image 66
Grzegorz Oledzki Avatar answered Oct 28 '25 23:10

Grzegorz Oledzki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!