Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading