Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use argparse parse_args to parse arguments as a string in python? [duplicate]

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?

like image 275
Mr.cysl Avatar asked Aug 14 '26 13:08

Mr.cysl


1 Answers

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))
like image 125
blhsing Avatar answered Aug 16 '26 02:08

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!