Python 即使使用具有相似名称的参数调用脚本,ArgParse 仍然有效

Python ArgParse works even though script is called with argument with similar name

我有以下代码:

import argparse

# Create the parser
parser = argparse.ArgumentParser("ArgParse intro")
# Add an argument

mand_arg_group = parser.add_argument_group("Mandatory arguments")
mand_arg_group.add_argument('--name', type = str, required = True, help = "This is the name of the person we are processing")

# Add more arguments
# If required is missing it is considered to be False
opt_arg_group = parser.add_argument_group("Optional arguments")
opt_arg_group.add_argument('--age', type = int,  help = "This is the age of the person we are processing")
# nargs specifies how many arguments to expect. If we don't know how many values the user will input we can use nargs='+'
opt_arg_group.add_argument('--tasks', type = int,  help = "These are the IDs of the tasks this person has completed ", nargs = '+')

# Mutually exclusive arguments
mut_ex_group = parser.add_mutually_exclusive_group()
mut_ex_group.add_argument('--day', type = str, help = "Day shift")
mut_ex_group.add_argument('--night', type = str, help = "Night shift")

# Parse the arguments
args = parser.parse_args()

if args.day:
    shift = args.day
else:
    shift = args.night
    
output_string = f"{args.name} has {args.age} years and completed tasks with the following IDs: {args.tasks}. {args.name} is working the {shift} shift"
print(output_string)

我用两种不同的方式调用了同一个脚本,它仍然有效:

  1. 第一种方式:python argparse_intro.py --name NAME1 --tasks 90 90 90
  2. 第二种方式:python argparse_intro.py --name NAME1 --task 90 90 90

似乎我拼写 task 或 tasks 都没关系,参数解析器将识别值和变量并打印出正确的消息而不会抛出错误

parse_args 接受 any unique prefix 的长选项名称:

The parse_args() method by default allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option):

如果您定义了第二个选项,例如 --taskserver,那么 --task 会引发错误,因为 parse_args 无法判断您的意思是 --tasks --taskserver。 (--tasks 本身作为选项的全名是明确的,而不是 --taskserver 的缩写。)

您可以通过将 allow_abbrev 设置为 false 来强制解析器忽略缩写。

parser = argparse.ArgumentParser("ArgParse intro", allow_abbrev=False)