Python 如何迭代参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27181084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to iterate over arguments
提问by user3654650
I have such script:
我有这样的脚本:
import argparse
parser = argparse.ArgumentParser(
description='Text file conversion.'
)
parser.add_argument("inputfile", help="file to process", type=str)
parser.add_argument("-o", "--out", default="output.txt",
help="output name")
parser.add_argument("-t", "--type", default="detailed",
help="Type of processing")
args = parser.parse_args()
for arg in args:
print(arg)
But it doesnt work. I get error:
但它不起作用。我得到错误:
TypeError: 'Namespace' object is not iterable
How to iterate over arguments and their value?
如何迭代参数及其值?
采纳答案by James Sapam
Please add 'vars' if you wanna iterate over namespace object:
如果要遍历命名空间对象,请添加“vars”:
for arg in vars(args):
print arg, getattr(args, arg)
回答by Christophe Biocca
Namespaceobjects aren't iterable, the standard docs suggest doing the following if you want a dictionary:
Namespace对象不可迭代,如果您想要字典,标准文档建议执行以下操作:
>>> vars(args)
{'foo': 'BAR'}
So
所以
for key,value in vars(args).iteritems():
# do stuff
To be honest I'm not sure why you want to iterate over the arguments. That somewhat defeats the purpose of having an argument parser.
老实说,我不确定您为什么要遍历参数。这在某种程度上违背了拥有参数解析器的目的。
回答by Victor Wong
ArgumentParser.parse_argsreturns a Namespaceobject instead of an iterable arrays.
ArgumentParser.parse_args返回一个Namespace对象而不是一个可迭代的数组。
For your reference, https://docs.python.org/3/library/argparse.html#parsing-arguments
供您参考,https://docs.python.org/3/library/argparse.html#parsing-arguments
ArgumentParser parses arguments through the parse_args() method. This will inspect the command line, convert each argument to the appropriate type and then invoke the appropriate action.
And it is not supposed to be used like that. Consider your use case, in the doc, it says argparsewill figure out how to parse those out of sys.argv., which means you don't have to iterate over those arguments.
它不应该这样使用。考虑您的用例,在文档中,它说argparse将弄清楚如何从sys.argv. ,这意味着您不必迭代这些参数。
回答by hpaulj
After
后
args = parser.parse_args()
to display the arguments, use:
要显示参数,请使用:
print args # or print(args) in python3
The argsobject (of type argparse.Namespace) isn't iterable (i.e. not a list), but it has a .__str__method, which displays the values nicely.
的args(的类型的对象argparse.Namespace)没有可迭代(即,不是一个列表),但它有一个.__str__方法,它很好地显示的值。
args.outand args.typegive the values of the 2 arguments you defined. This works most of the time. getattr(args, key)the most general way of accessing the values, but usually isn't needed.
args.out并args.type给出您定义的 2 个参数的值。这在大多数情况下都有效。 getattr(args, key)访问值的最通用方式,但通常不需要。
vars(args)
turns the namespace into a dictionary, which you can access with all the dictionary methods. This is spelled out in the docs.
将命名空间变成一个字典,您可以使用所有字典方法访问它。这在docs.
ref: the Namespace paragraph of the docs - https://docs.python.org/2/library/argparse.html#the-namespace-object
参考:文档的命名空间段落 - https://docs.python.org/2/library/argparse.html#the-namespace-object
回答by mork
I'm using args.__dict__, which lets you access the underlying dict structure.
Then, its a simple key-value iteration:
我正在使用args.__dict__,它可以让您访问底层的 dict 结构。然后,它是一个简单的键值迭代:
for k in args.__dict__:
print k, args.__dict__[k]
回答by BoboDarph
Parsing the _actions from your parser seems like a decent idea. Instead of running parse_args() and then trying to pick stuff out of your Namespace.
从解析器解析 _actions 似乎是一个不错的主意。而不是运行 parse_args() 然后尝试从您的命名空间中挑选东西。
import argparse
parser = argparse.ArgumentParser(
description='Text file conversion.')
parser.add_argument("inputfile", help="file to process", type=str)
parser.add_argument("-o", "--out", default="output.txt",
help="output name")
parser.add_argument("-t", "--type", default="detailed",
help="Type of processing")
options = parser._actions
for k in options:
print(getattr(k, 'dest'), getattr(k, 'default'))
You can modify the 'dest' part to be 'choices' for example if you need the preset defaults for a parameter in another script (by returning the options in a function for example).
例如,如果您需要另一个脚本中参数的预设默认值(例如,通过返回函数中的选项),您可以将“dest”部分修改为“选择”。

