How can I use python's argparse with a predefined argument string?
Another option is to use shlex.split. It it especially very convenient if you have real CLI arguments string:
import shlex
argString = '-vvvv -c "yes" --foo bar --some_flag'
args = parser.parse_args(shlex.split(argString))
parser.parse_args()
expects a sequence in the same form as sys.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'])
Just like the default sys.argv
is a list, your arguments have to be a list as well.
args = parser.parse_args([argString])