3

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?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
plasmid
  • 33
  • 4
  • 1
    with your current configuration you can do `--input=...`. Arguments without a prefix are reserved for positional arguments – Alexander Apr 03 '23 at 17:44
  • Short of rewriting significant portions of `argparse` itself, you can't have a positional argument like `input=foo` be recognized as a form of `--input=foo`. If it's required, I would suggest making it a positional argument. You could require that it be provided in the form of `input=foo` via a custom `type` argument to `add_argument`, but that would be redundant because it wouldn't let you specify different arguments in an arbitrary order. – chepner Apr 03 '23 at 17:45
  • 1
    See: https://stackoverflow.com/questions/27146262/create-variable-key-value-pairs-with-argparse-python – SimonUnderwood Apr 03 '23 at 17:47

1 Answers1

1

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.

kichik
  • 33,220
  • 7
  • 94
  • 114