Add argparse arguments from external modules

2024/10/12 12:26:00

I'm trying to write a Python program that could be extended by third parties. The program will be run from the command line with whatever arguments are supplied.

In order to allow third parties to create their own modules, I've created the following (simplified) base class:

class MyBaseClass(object):def __init__(self):self.description = ''self.command = ''def get_args(self):# code that I can't figure out to specify argparse arguments here# args = []# arg.append(.....)return args

Any arguments that they supply via get_args() will be added to a subparser for that particular module. I want them to be able to specify any type of argument.

I'm not sure of the best way to declare and then get the arguments from the subclassed modules into my main program. I successfully find all subclasses of MyBaseClass and loop through them to create the subparsers, but I cannot find a clean way to add the individual arguments to the subparser.

Here is the current code from the main program:

for module in find_modules():m = module()subparser_dict[module.__name__] = subparsers.add_parser(m.command, help=m.help)for arg in m.get_args():subparser_dict[module.__name__].add_argument(...)

How can I best specify the arguments in the external modules via get_args() or similar and then add them to the subparser? One of my failed attempts looked like the following, which doesn't work because it tries to pass every possible option to add_argument() whether it has a value or is None:

            subparser_dict[module.__name__].add_argument(arg['long-arg'],action=arg['action'],nargs=arg['nargs'],const=arg['const'],default=arg['default'],type=arg['type'],choices=arg['choices'],required=arg['required'],help=arg['help'],metavar=arg['metavar'],dest=arg['dest'],)
Answer

Without trying to fully understand your module structure, I think you want to be able to provide the arguments to a add_argument call as objects that you can import.

You could, for example, provide a list of positional arguments, and dictionary of keyword arguments:

args=['-f','--foo']
kwargs={'type':int, 'nargs':'*', 'help':'this is a help line'}parser=argparse.ArgumentParser()
parser.add_argument(*args, **kwargs)
parser.print_help()

producing

usage: ipython [-h] [-f [FOO [FOO ...]]]optional arguments:-h, --help            show this help message and exit-f [FOO [FOO ...]], --foo [FOO [FOO ...]]this is a help line

In argparse.py, the add_argument method (of a super class of ArgumentParser), has this general signature

def add_argument(self, *args, **kwargs):

The code of this method manipulates these arguments, adds the args to the kwargs, adds default values, and eventually passes kwargs to the appropriate Action class, returning the new action. (It also 'registers' the action with the parser or subparser). It's the __init__ of the Action subclasses that lists the arguments and their default values.

https://en.xdnf.cn/q/69652.html

Related Q&A

Cosine similarity for very large dataset

I am having trouble with calculating cosine similarity between large list of 100-dimensional vectors. When I use from sklearn.metrics.pairwise import cosine_similarity, I get MemoryError on my 16 GB ma…

What exactly are the csv modules Dialect settings for excel-tab?

The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the formatpreferred by Excel,” or “read data from this file which wa…

Python: how to make a recursive generator function

I have been working on generating all possible submodels for a biological problem. I have a working recursion for generating a big list of all the submodels I want. However, the lists get unmanageably …

Change default options in pandas

Im wondering if theres any way to change the default display options for pandas. Id like to change the display formatting as well as the display width each time I run python, eg:pandas.options.display.…

python-messaging Failed to handle HTTP request

I am using the code below to try to send an MMS message with python-messaging https://github.com/pmarti/python-messaging/blob/master/doc/tutorial/mms.rst Although the connection seems to go smoothly I …

Plotting confidence and prediction intervals with repeated entries

I have a correlation plot for two variables, the predictor variable (temperature) on the x-axis, and the response variable (density) on the y-axis. My best fit least squares regression line is a 2nd or…

Saving and Loading of dataframe to csv results in Unnamed columns

prob in the title. exaple:x=[(a,a,c) for i in range(5)] df = DataFrame(x,columns=[col1,col2,col3]) df.to_csv(test.csv) df1 = read_csv(test.csv)Unnamed: 0 col1 col2 col3 0 0 a a c 1 …

Python: print specific character from string

How do I print a specific character from a string in Python? I am still learning and now trying to make a hangman like program. The idea is that the user enters one character, and if it is in the word…

Python AttributeError: module string has no attribute maketrans

I am receiving the below error when trying to run a command in Python 3.5.2 shell:Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "copyrig…

How to add attribute to class in python

I have: class A:a=1b=2I want to make as setattr(A,c)then all objects that I create it from class A has c attribute. i did not want to use inheritance