How to allow required arguments to be omitted when a specific flag is used?

Viewed 49

My code is as follows.

__version__ = 'v10'

class MyHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
       def _get_help_string(self, action):
              return action.help

def main():
       parser = argparse.ArgumentParser(
              formatter_class=MyHelpFormatter,
              description=__version__
       )

       parser.print_usage = parser.print_help

       parser.add_argument("file", help="path to file/directory")

       parser.add_argument(
              "-t",
              "--type",
              type=str,
              default=False,
              help="file type",
       )

       parser.add_argument(
              "-c",
              "--config",
              action="store_true",
              help="change custom text",
       )

       parser.add_argument(
              "-v",
              "--version",
              action='version',
              version=__version__,
              help="thumb-gen version",
       )

In my code, it always requires the 'file' argument. It's ok.

Now I want call a function when it call with '--config' argument. But when I run main.py --config it also require the 'file' argument.

How to use the '-config' argument without entering the required argument?

1 Answers

There are two ways to solve this. First, you could make the file argument optional. After parsing is finished, your code checks if the --config flag was present ― if it wasn’t, then check if the file argument was given. If not, exit with an appropriate error message.

Alternatively you can use two parsers. The first one looks for --config and sets a flag (e.g. do_config = True); it does not require a file argument. Then use a second parser that only requires a file argument if do_config is False.

Related