using a variable keyword for an optional argument name with python argparse

拟墨画扇 提交于 2019-12-23 04:43:11

问题


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?


回答1:


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

Using argparse with function that takes **kwargs argument

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



回答2:


Apologies in advance if I didn't understand exactly what you want to do. But from your description, if I were implementing this, I might try something like the following. Here I make mass and spin optional inputs and set their default values, so the only required input is the file name.

Example code:

# q.py test code

import argparse

parser = argparse.ArgumentParser(prog='q.py')
parser.add_argument('file', help='filename')
parser.add_argument('-m', default=100, type=int, help='integer mass value')
parser.add_argument('-s', nargs=2, default=[0.5,1.0], type=float, help='spin values without comma')

args=parser.parse_args()

print('file:', args.file)
print('mass:', args.m)
print('spin:', tuple(args.s))

Some command line calls:

$ python q.py -h
usage: q.py [-h] [-m M] [-s S S] file

positional arguments:
file        filename

optional arguments:
-h, --help  show this help message and exit
-m M        integer mass value
-s S S      spin values without comma

$ python q.py test.csv
file: test.csv
mass: 100
spin: (0.5, 1.0)

$ python q.py test.csv -m 99 -s 0.2 1.1
file: test.csv
mass: 99
spin: (0.2, 1.1)

And I think you can call initialize your reader like this:

reader = AsciiFileReducer(args.file, mass = (args.m, float("inf")), spin = tuple(args.s))


来源:https://stackoverflow.com/questions/34384865/using-a-variable-keyword-for-an-optional-argument-name-with-python-argparse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!