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

2024/10/15 11:21:55

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?

Answer

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)}
https://en.xdnf.cn/q/117835.html

Related Q&A

Error while setting up MongoDB with django using django mongodb engine on windows

Steps I followed :pip install git+htp://github.com/django-nonrel/[email protected]It did not work, so I downloaded the zip from the site "htp://github.com/django-nonrel/django" and pasted the…

Python login page with pop up windows

I want to access webpages and print the source codes with python, most of them require login at first place. I have similar problem before and I have solved it with the following code, because they are…

Calculate Scipy LOGNORM.CDF() and get the same answer as MS Excel LOGNORM.DIST

I am reproducing a chart in a paper using the LOGNORM.DIST in Microsoft Excel 2013 and would like to get the same chart in Python. I am getting the correct answer in excel, but not in python.In excel …

Python MySQLdb cursor.execute() insert with varying number of values

Similar questions have been asked, but all of them - for example This One deals only with specified number of values.for example, I tried to do this the following way:def insert_values(table, columns, …

Searching in a .txt file and Comparing the two values of a string in python?

"cadence_regulatable_result": "completeRecognition","appserver_results": {"status": "success","final_response": 0,"payload": {"…

How to perform an HTTP/XML authentication with requests

I am trying to authenticate to Docushare with Python 3.4 using requests 2.7. I am relatively new to Python and to the requests module but Ive done a lot of reading and am not able to make any more prog…

webPy Sessions - Concurrent users use same session and session timeout

I have a webPy app using sessions for user authentication. Sessions are initiated like so:web.config.debug=Falsestore = web.session.DiskStore(/path_to_app/sessions) if web.config.get(_session) is None:…

get text content from p tag

I am trying to get description text content of each block on this page https://twitter.com/search?q=data%20mining&src=typd&vertical=default&f=users. html for p tag looks like<p class=&q…

Python - making a function that would add - between letters

Im trying to make a function, f(x), that would add a "-" between each letter:For example:f("James")should output as:J-a-m-e-s-I would love it if you could use simple python function…

python script keeps converting dates to utc

I have the following:import psycopg2 from openpyxl import Workbook wb = Workbook() wb.active =0 ws = wb.active ws.title = "Repair" ws.sheet_properties.tabColor = "CCFFCC"print(wb.sh…