Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using fromfile_prefix_chars with multiple arguments (nargs="*")

I would like to use file arguments in python argparse with lines in the file that look like this:

--contour_levels=-4 -2 0 2 4

or:

--contour_levels -4 -2 0 2 4

Is there an easy way to do this? I know I can use the first one and then list the other levels one per line but this looks ridiculous.

Thanks!

like image 665
Eli S Avatar asked May 22 '26 14:05

Eli S


1 Answers

From the docs:

https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.convert_arg_line_to_args

def convert_arg_line_to_args(self, arg_line):
    for arg in arg_line.split():
        if not arg.strip():
            continue
        yield arg

This function replaces the one the parser uses to read lines from your file. You could subclass ArgumentParser and add this function. Or you could 'kludge' it by replacing the bound method of the parser with this function (without the self - see comment).

parser = argparse.ArgumentParser(...)
parser.convert_arg_line_to_args = convert_arg_line_to_args

The idea is to take a line from your file, and return (as a generator) strings one by one. If this doesn't work as given, it shouldn't be hard to tweak.

p.s. The default version, which returns one string per line is

def convert_arg_line_to_args(self, arg_line):
    return [arg_line]

look at the code for ArgumentParser._read_args_from_files if you have more questions on how it is used. This is the function takes the list of strings from sys.argv[1:] and returns a new one with your file contents added.

like image 76
hpaulj Avatar answered May 25 '26 04:05

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!