i have a program that takes 3 parameters: volume, weight, and model_path. Currently, i have:
volume = int(args[0])
weight = int(args[1])
model_path = args[2]
so i have to execute it like this: python3 example.py 713 382 model.pkl
. I want to be able to do it like this: python3 example.py --weight=500 --volume=437 --model=model.pkl
, but in any order (so python3 example.py --volume=3100 --model=model.pkl --weight=472
).
I tried
volume = int(args["--volume"])
weight = int(args["--weight"])
model_path = args["--model"]
and it said args could only be type slice or int, not string.
CodePudding user response:
Ignoring the idea of reimplementing the argparse
module, just use that module. For example,
import argparse
p = argparse.ArgumentParser()
p.add_argument('--volume', type=int)
p.add_argument('--weight', type=int)
p.add_argument('--model')
args = p.parse_args()
The result will be an instance of argparse.Namespace
, which is just a very simple object with attributes associated with each argument you defined. For example, if you specify --weight=500
or --weight 500
, then args.weight == 500
.