jmd_dk
jmd_dk

Reputation: 13090

Python argparse: Leading dash in argument

I'm using Python's argparse module to parse command line arguments. Consider the following simplified example,

# File test.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store')
parser.add_argument('-a', action='append')
args = parser.parse_args()
print(args)

which can successfully be called like

python test.py -s foo -a bar -a baz

A single argument is required after -s and after each -a, which may contain spaces if we use quotation. If however an argument starts with a dash (-) and does not contain any spaces, the code crashes:

python test.py -s -begins-with-dash -a bar -a baz

error: argument -s: expected one argument

I get that it interprets -begins-with-dash as the beginning of a new option, which is illegal as -s has not yet received its required argument. It's also pretty clear though that no option with the name -begins-with-dash has been defined, and so it should not interpret it as an option in the first place. How can I make argparse accept arguments with one or more leading dashes?

Upvotes: 16

Views: 8608

Answers (2)

Joey Harrington
Joey Harrington

Reputation: 300

You can force argparse to interpret an argument as a value by including an equals sign:

python test.py -s=-begins-with-dash -a bar -a baz
Namespace(a=['bar', 'baz'], s='-begins-with-dash')

Upvotes: 27

jeremysprofile
jeremysprofile

Reputation: 11435

If you are instead trying to provide multiple values to one argument:

parser.add_argument('-a', action='append', nargs=argparse.REMAINDER)

will grab everything after -a on the command line and shove it in a.

python test.py -toe -a bar fi -fo -fum -s fee -foo
usage: test.py [-h] [-s S] [-a ...]
test.py: error: unrecognized arguments: -toe

python test.py -a bar fi -fo -fum -s fee -foo
Namespace(a=[['bar', 'fi', '-fo', '-fum', '-s', 'fee', '-foo']], s=None)

Note that even though -s is a recognized argument, argparse.REMAINDER adds it to the list of args found by -a since it is after -a on the command line

Upvotes: 6

Related Questions