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?

Mr.cysl
  • 1,494
  • 6
  • 23
  • 37

1 Answers1

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))
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 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? – Mr.cysl Apr 05 '19 at 01:48
  • 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. – blhsing Apr 05 '19 at 03:48