[英]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?另外,如何从 IDLE shell 运行它? I use the command 'python myprogram.py -x foo -y bar -z cheese' and it gives me a syntax error
我使用命令“python myprogram.py -x foo -y bar -z cheese”,它给了我一个语法错误
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__
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:获取文档中建议的参数值的规范方法是像您一样使用
vars
并按名称访问参数值:
argv = vars(args)
one = argv['one']
two = args['two']
three = argv['three']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.