How to save argparse values ​​in variables?

I am trying to add command line options to my script using the following code:

import argparse

parser = argparse.ArgumentParser('My program')
parser.add_argument('-x', '--one')
parser.add_argument('-y', '--two')
parser.add_argument('-z', '--three')

args = vars(parser.parse_args())

foo = args['one']
bar = args['two']
cheese = args['three']

Is this being done right?

Also, how can I run it from the IDLE shell? I use the command 'python myprogram.py -x foo -y bar -z cheese' and this gives me a syntax error

+4
source share
2 answers

This will work, but you can simplify it a bit:

args = parser.parse_args()

foo = args.one
bar = args.two
cheese = args.three
+13
source

use args.__dict__

args.__dict__["one"]
args.__dict__["two"]
args.__dict__["three"]
+2
source

Source: https://habr.com/ru/post/1532920/


All Articles