How to take two positional arguments when optinal isn't set in argparse

Viewed 132

I want to write a argparse command that needs two postional arguments when I don't set a optional argument. In my case it's like I want to call it with two necessary parameters but when I say python3 test.py -gui I want that you don't need this two arguments, because then you are using the gui.

Thx

1 Answers

This is what I was proposing in the comments:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--gui', action='store_true', help="use GUI")
parser.add_argument('args', nargs='*')
cmdargs = parser.parse_args()
nargs = len(cmdargs.args)
nargs_expected = 0 if cmdargs.gui else 2
if nargs != nargs_expected:
    parser.error(f"{nargs_expected} arguments were expected, but got {nargs}")
Related