3

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?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
trueThari
  • 105
  • 1
  • 8
  • 2
    Does this answer your question? [Require either of two arguments using argparse](https://stackoverflow.com/questions/11154946/require-either-of-two-arguments-using-argparse) – Maurice Meyer Apr 14 '21 at 15:03
  • Your code never calls `parser.parse_args()` or `main()`, and there's a lot of stuff that seems unrelated to the problem. Please provide a [mre]. I wrote one [here in a gist](https://gist.github.com/wjandrea/065e9034095bfbcf169bc3b49fcd0c99) if you want to use it. – wjandrea Apr 14 '21 at 15:37
  • @MauriceMeyer The 'file' argument requires a flag when I use that solution. I do not need a flag for the 'file' in my code. Is there a solution to this? – trueThari Apr 14 '21 at 16:10
  • Often the cleanest solution is to make `--file` optional with a good default. That way you don't care whether the user supplied the value or not. – hpaulj Apr 14 '21 at 16:34
  • Something like this: `group.add_argument('--file', nargs='?')` or default value. – Maurice Meyer Apr 14 '21 at 16:35

1 Answers1

0

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.

inof
  • 465
  • 3
  • 7