I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.
import argparse
parser = argparse.ArgumentParser(description='Argparse Test script')
parser.add_argument("param", help='some parameter')
argString = 'someTestFile'
print(argString)
args = parser.parse_args(argString)
If I run this script I get this output:
~/someTestFile
usage: argparsetest.py [-h] param
argparsetest.py: error: unrecognized arguments: o m e T e s t F i l e
The ~/someTestFile is somehow transformed in o m e T e s t F i l e. As already mentioned, it works if I pass the filename from the terminal.
I could imagine, that this has something to do with string encodings. Does someone has an idea how to fix this?
parser.parse_args()expects a sequence in the same form assys.argv[1:]. If you treat a string like a sys.argv sequence, you get['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']. ‘s’ becomes the relevant argument, and then the rest of the string is unparseable.Instead, you probably want to pass in
parser.parse_args(['someTestFile'])