Are there any ways to set the argparse.ArgumentParser()
to a string in the program in Python?
For example, I have a string s = "A rocket in the sky --height 512 --width 512"
declared when running the program (instead of the user inputs in the command prompt), how can i get the values of height and width as int?
CodePudding user response:
You can pass an explicit list of arguments to the ArgumentParser.parse_args
method; just .split()
your string and use that:
import argparse
s = "A rocket in the sky --height 512 --width 512"
p = argparse.ArgumentParser()
p.add_argument('--height')
p.add_argument('--width')
p.add_argument('everything_else', nargs='*')
args = p.parse_args(s.split())
print(args)
The above code will output:
Namespace(height='512', width='512', everything_else=['A', 'rocket', 'in', 'the', 'sky'])
CodePudding user response:
You can use re.split()
to match --height NNN
and build a custom list of arguments, which can then be passed to parse_args
.
import argparse
import re
def parse_args(s: str) -> argparse.Namespace:
parts = re.split("(--\w \d )", s)
args = []
for t in parts:
if t.startswith("--"):
args.extend(t.split())
parser = argparse.ArgumentParser()
parser.add_argument("--height", type=int)
parser.add_argument("--width", type=int)
return parser.parse_args(args)
namespace = parse_args("A rocket in the sky --height 512 --width 1234")
print(namespace)