简体   繁体   中英

How to store 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 the correct way to do this?

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

That will work, but you can simplify it a bit like this:

args = parser.parse_args()

foo = args.one
bar = args.two
cheese = args.three

use args.__dict__

args.__dict__["one"]
args.__dict__["two"]
args.__dict__["three"]

I'm currently using

import argparse
import sys

parser = argparse.ArgumentParser('My program')
parser.add_argument('--one')
parser.add_argument('--two')
parser.add_argument('--three')

parser.parse_args(namespace=sys.modules[__name__])

print(f"{one}, {two}, {three}")

Is there a reason not to do this?

The canonical way to get the values of the arguments that is suggested in the documentation is to use vars as you did and access the argument values by name:

argv = vars(args)

one = argv['one']
two = args['two']
three = argv['three']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM