我在我的 Python 脚本中使用argparse :
import argparse
argParser = argparse.ArgumentParser(description="Testing argparse.")
argParser.add_argument(
"--use-something",
action="store_true",
help="use something in addition (default: %(default)s)"
)
cliArgs = argParser.parse_args()
print(cliArgs)
所以我希望脚本只接受--use-something选项,但实际上它接受它的任何不完整变体:
$ python --version
Python 3.9.6
$ python ./testing-argparse.py --help
usage: testing-argparse.py [-h] [--use-something]
Testing argparse.
optional arguments:
-h, --help show this help message and exit
--use-something use something in addition (default: False)
$ python ./testing-argparse.py
Namespace(use_something=False)
$ python ./testing-argparse.py --use-something
Namespace(use_something=True)
$ python ./testing-argparse.py --use-some
Namespace(use_something=True)
$ python ./testing-argparse.py --use
Namespace(use_something=True)
$ python ./testing-argparse.py --u
Namespace(use_something=True)
$ python ./testing-argparse.py -u
usage: testing-argparse.py [-h] [--use-something]
testing-argparse.py: error: unrecognized arguments: -u
$ python ./testing-argparse.py --use-somethings
usage: testing-argparse.py [-h] [--use-something]
testing-argparse.py: error: unrecognized arguments: --use-somethings
不确定,如果它是一个错误,或者我是否缺少一些“更严格”解析的配置选项?