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