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?