Skip to content Skip to sidebar Skip to footer

Python Argparse Assertionerror From Metavar `[[user@]host:]file`

Argparse 1.1 or 1.4 fails with AssertionError - the weird regex that reads the metavar value seems to blow up argparse - Possibly related to Python argparse AssertionError when num

Solution 1:

The workaround is to create a custom help formatter and do post-processing using a sanitized value. One way to do so can be like so:

classMyHelpFormatter(argparse.HelpFormatter):

    def_format_usage(self, usage, actions, groups, prefix):
        result = super(MyHelpFormatter, self)._format_usage(
            usage, actions, groups, prefix)
        return result.format(user_host_file='[[USER@]HOST]:FILE')

Then construct the parser using the custom formattter

parser = argparse.ArgumentParser(formatter_class=MyHelpFormatter)
parser.add_argument(
    'files',
    metavar='{user_host_file}',
    nargs=argparse.PARSER,
    )

Plugging the rest into the code supplied, something like this is produced

$ python demo.py 
('argparse', '1.1')
usage: demo.py [-h] [-a PTRN] [-b PTRN] [-c PTRN] [-d PTRN] [-e PTRN]
               [-f PTRN]
               [[USER@]HOST]:FILE ...
demo.py:error: too few arguments

Naturally, the exact strategy can be as simple as using the str.replace method in the formatter, or more complicated than the str.format method.

Solution 2:

Yes, there's a known bug in the argparseusage formatter. Characters in the metavar like brackets produce this assertion error. I could point out the bug/issue or explain the problem. But the simplest solution is to just change your METAVAR to something simpler. Put the extra information in the help line. Another simple option is to provide a custom usage parameter.

http://bugs.python.org/issue11874

Subclassing the HelpFormatter and replacing one or two methods is also good argparse practice. But that requires digging into the code, and understanding what needs to be replaced. The other answer is a good start. The changes suggest in the issue patch are more complicated because it is trying to be general purpose (including the handling of mutually exclusive groups and usage that can span several lines).

Post a Comment for "Python Argparse Assertionerror From Metavar `[[user@]host:]file`"