Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Differentiate between optional and mandatory in Pythons argparse

$
0
0

I am a bit confused with argparse but using it for years. Let's see this example:

$ ./argpars_debug.py foo --helpusage: argpars_debug.py [-h] [-d] [--version] inputpositional arguments:  inputoptions:  -h, --help   show this help message and exit  -d, --debug  --version    show program's version number and exit

Problem

The input argument is mandatory. But using --version without input is possible.

$ ./argpars_debug.py --version0.1.2

But using --debug without input is not possible:

$ ./argpars_debug.py --debugusage: argpars_debug.py [-h] [-d] [--version] inputargpars_debug.py: error: the following arguments are required: input

My Goal

I would like to use --debug with and without input.

$ ./argpars_debug.py --debug$ ./argpars_debug.py foo --debug

I can do this with --version. But I don't understand how I can modify this behavior.

The minimal working example

#!/usr/bin/env python3import argparseimport sysdef main():    parser = argparse.ArgumentParser()    parser.add_argument('input', type=str)    parser.add_argument('-d', '--debug', action='store_true')    parser.add_argument('--version', action='version', version='0.1.2')    return parser.parse_args()if __name__ == '__main__':    main()    print(f'{sys.argv=}')

Viewing all articles
Browse latest Browse all 23131

Trending Articles