python可选参数和可变量参数,在python argparse中使用变量关键字作为可选参数名称...

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))

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.

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?

解决方案

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

This has a couple of long answers with links to earlier questions.

Another option is to take a string and parse it with JSON.

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)}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值