is it possible to spit out help as default argument when nothing is passed? [closed]

StackOverflow https://stackoverflow.com/questions/21533201

  •  06-10-2022
  •  | 
  •  

Pergunta

In python's argparse, is it possible to spit out help as default argument when nothing is passed or if some Argparse Exception occurs?

Foi útil?

Solução

If having zero arguments should trigger the help message, that implies that at least one of your options isn't really optional. Make sure you have at least one positional argument (i.e., one whose name is not prefixed with "--") defined:

p = argparse.ArgumentParser()
p.add_argument("foo", help="Required argument")

Then, if your script isn't called with the argument for foo, the usage message should be triggered.

Outras dicas

The parser uses sys.argv[0] for the default prog value, and sys.argv[1:] as input to parse_args. You too can access, and even modify, that array.

import argparse
import sys

parser = argparse.ArgumentParser....
parser.add_argument...

if not sys.argv[1:]:
    # parser.print_help(); parser.exit()
    # or
    # parser.parse_args(['-h'])
    # or
    sys.argv.append('-h')

args = parser.parse_args()

# your code to use args
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top