Python3 中带开关的强制参数

mandatory argument with switch in Python3

我想要一个带有开关的强制性(必须有)参数 --switch。 但是 argparse-- 解释为可选参数并且不检查它们的存在。

有办法解决这个问题吗?

#!/usr/bin/env python3    
import sys
import argparse

parser = argparse.ArgumentParser(description=__file__)

# must have
parser.add_argument('--switch', metavar='switch', type=str)

sys.exit()

只需使用 required 参数:

parser.add_argument('--switch', metavar='switch', type=str, required=True)

引用文档:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. To make an option required, True can be specified for the required= keyword argument to add_argument()

[...]

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.