在python argparse中使用变量关键字作为可选参数名称 [英] using a variable keyword for an optional argument name with python argparse
问题描述
我正在将argparse用于我正在编写的python脚本.该脚本的目的是处理存储表格数据的大型ascii文件.该脚本只是为我编写的类提供了一个方便的前端,该类允许在表格数据上进行任意数量的即时剪切.在类中,用户可以传入变量名称关键字参数,该参数带有绑定到变量的两个元素的元组.元组在任何列上定义一个上下限,其名称与变量名称关键字相对应.例如:
I am using argparse for a python script I am writing. The purpose of the script is to process a large ascii file storing tabular data. The script just provides a convenient front-end for a class I have written that allows an arbitrary number of on-the-fly cuts to be made on the tabular data. In the class, the user can pass in a variable-name keyword argument with a two-element tuple bound to the variable. The tuple defines a lower and upper bound on whatever column with a name that corresponds to the variable-name keyword. For example:
reader = AsciiFileReducer(fname, mass = (100, float("inf")), spin = (0.5, 1))
此 reader 实例将忽略输入 fname 的所有行,但质量<100> em> 0.5的行除外.旋转< 1 .输入的 fname 可能还有许多其他列,但是只有 mass 和 spin 会在其上放置切口.
This reader instance will then ignore all rows of the input fname except those with mass > 100 and 0.5 < spin < 1. The input fname likely has many other columns, but only mass and spin will have cuts placed on them.
我希望我正在编写的脚本保留此功能,但是我不知道如何使用argparse.add_argument添加具有变量名的参数.我的课程允许使用任意数量的可选参数,每个参数均具有未指定的名称,其中为名称选择的字符串本身就是有意义的. python的** kwargs功能使之成为可能. argparse有可能吗?
I want the script I am writing to preserve this feature, but I do not know how to allow for arguments with variable names to be added with argparse.add_argument. My class allows for an arbitrary number of optional arguments, each with unspecified names where the string chosen for the name is itself meaningful. The **kwargs feature of python makes this possible. Is this possible with argparse?
推荐答案
以前已经提出了通过argparse接受任意key:value对的问题.例如:
The question of accepting arbitrary key:value pairs via argparse has come up before. For example:
将argparse与带有** kwargs参数的函数一起使用
这有几个很长的答案,并提供了到较早问题的链接.
This has a couple of long answers with links to earlier questions.
另一种选择是获取一个字符串,并使用JSON对其进行解析.
Another option is to take a string and parse it with JSON.
但这是基于nargs
和append
操作类型的快速选择:
But here's a quick choice building on nargs
, and the append
action type:
parser=argparse.ArgumentParser()
parser.add_argument('-k','--kwarg',nargs=3,action='append')
一个示例输入,产生一个带有列表列表的名称空间:
A sample input, produces a namespace with list of lists:
args=parser.parse_args('-k mass 100 inf -k spin 0.5 1.0'.split())
Namespace(kwarg=[['mass', '100', 'inf'], ['spin', '0.5', '1.0']])
可以将它们转换为具有以下表达式的字典:
they could be converted to a dictionary with an expression like:
vargs={key:(float(v0),float(v1)) for key,v0,v1 in args.kwarg}
可以通过以下方式传递给您的函数:
which could be passed to your function as:
foo(**vargs)
{'spin': (0.5, 1.0), 'mass': (100.0, inf)}
这篇关于在python argparse中使用变量关键字作为可选参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!