My original code like the following works well with command line calls. However, is there a way that I could parse a list of arguments as a string in Python?
Example:
parser = argparse.ArgumentParser()
parser.parse_args()
And you call:
python test.py <args like --a 1 --b 2 ...>
Then if I have a string s which is the args list above, is there a way I could get that parsed?
You can split the string into a list and pass it to parse_args:
parser.parse_args(s.split())
Or if the string contains shell-like syntax such as quotes and escape characters, use shlex.split to split the string:
import shlex
parser.parse_args(shlex.split(s))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With