I am parsing an argument input:
python parser_test.py --p "-999,-99;-9"
I get this error:
parser_test.py: error: argument --p: expected one argument
Is there a particular reason why including '-' in the optional argument
"-999,-99;-9"
throws the error even while within double quotes? I need to be able to include the '-' sign.
Here is the code:
import argparse
def main():
parser = argparse.ArgumentParser(description='Input command line arguments for the averaging program')
parser.add_argument('--p', help='input the missing data filler as an integer')
args = parser.parse_args()
if __name__=='__main__':
main()
The quotes do nothing to alter how argparse
treats the -
; the only purpose they serve is to prevent the shell from treating the ;
as a command terminator.
argparse
looks at all the arguments first and identifies which ones might be options, regardless of what options are actually defined, by checking which ones start with -
. It makes an exception for things that could be negative numbers (like -999
), but only if there are no defined options that look like numbers.
The solution is to prevent argparse
from seeing -999,-99;-9
as a separate argument. Make it part of the argument that contains the -p
using the --name=value
form.
python parser_test.py --p="-999,-99;-9"
You can also use "--p=-999,-99;-9"
or --p=-999,-99\;-9
, among many other possibilities for writing an argument that will cause the shell to parse your command line as two separate commands, python parser_test.py --p-999,-99
and -9
.