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

Python argparse required?

How can I make it a required argument only if I don’t select another option, so when I select version it shouldn’t require -f, but the rest of the time it should be required?

parser = argparse.ArgumentParser(
        description="This script will check the uri's from XXX")

parser.add_argument(
    "-f", "--file", help="XXX export file to use", required=True)
parser.add_argument("-c", "--check", action="store_true",
                    help="Check the uri's")
parser.add_argument("-p", "--passwords", action="store_true",
                    help="Check the weak passwords")
parser.add_argument("-V", "--version", action="store_true",
                    help="Show version")
self.params = parser.parse_args(self.get_params())

>Solution :

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

So, two things:

  1. In the general case, this is done with add_mutually_exclusive_group(required=True) and adding the mutually exclusive arguments to that group (this isn’t exactly what you want, since it won’t allow you to pass both, but it’s close enough).
  2. In this specific case, you should be using the action='version' action for displaying the version, which exists specifically for this purpose, and leave -f plain required=True as you’ve already written 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