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

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

  •  06-10-2022
  •  | 
  •  

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

有帮助吗?

解决方案

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.

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top