3

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?

0

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I am getting an error like this: ArgumentError: argument --data_dir: conflicting option string: --data_dir, where data_dir is one of the arguments I defined. Do you have any thoughts?
There is another option you define that has the same prefix as --data_dir so it's considered conflicting. You can fix this by naming the option something else.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.