Search code examples
pythonargparse

How to specify arguments in the form of `input=<INPUT>` in argparse


I could use argparse to add command line arguments in the form of

  • -i <INPUT> or
  • --input <INPUT>.

I want to instead have the command be in the form of input=<INPUT>.

Code

What I currently have:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help = "Input is a required field", required = True)

Issue

When I change '--input' to 'input=' it doesn't work.

Question

How to specify the format so that 'input=' followed by the input string can be given as valid command line argument?


Solution

  • You don't need to explicitly ask for support of =. It should just work.

    >>> import argparse
    >>>
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('-i', '--input', help = "Input is a required field", required = True)
    _StoreAction(option_strings=['-i', '--input'], dest='input', nargs=None, const=None, default=None, type=None, choices=None, required=True, help='Input is a required field', metavar=None)
    >>> parser.parse_args(['--input=foobar'])
    Namespace(input='foobar')
    >>>
    

    If you want to get rid of the double dashes too, you may have to write your own argument parsing code. I don't see any documentation suggesting it's supported. You can replace dash with something else using prefix_chars, but you can't completely get rid of it.