在 python argparse 中使用变量关键字作为可选参数名称 [英] using a variable keyword for an optional argument name with python argparse

查看:33
本文介绍了在 python argparse 中使用变量关键字作为可选参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 argparse 用于我正在编写的 Python 脚本.该脚本的目的是处理存储表格数据的大型 ascii 文件.该脚本只是为我编写的一个类提供了一个方便的前端,允许对表格数据进行任意数量的即时剪切.在类中,用户可以传入一个变量名关键字参数,其中包含绑定到变量的二元素元组.该元组定义了名称与 variable-name 关键字对应的任何列的下限和上限.例如:

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 的所有行,除了那些 mass > 1000.5 自旋<1.输入 fname 可能有许多其他列,但只有 massspin 会在它们上面放置切割.

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 接受任意键值对的问题之前已经出现过.例如:

The question of accepting arbitrary key:value pairs via argparse has come up before. For example:

使用带有 **kwargs 参数的函数的 argparse

这有几个很长的答案,并附有早期问题的链接.

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.

但是这里有一个基于 nargsappend 操作类型的快速选择:

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}

可以传递给您的函数:

foo(**vargs)
{'spin': (0.5, 1.0), 'mass': (100.0, inf)}

这篇关于在 python argparse 中使用变量关键字作为可选参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆