Python argparse:在添加其他参数之前处理某些参数

Python argparse: Processing Certain Arguments Before Adding Others

使用 python 的 argparse 库,我想处理前几个命令行参数并使用它们生成其他命令行参数的选项列表。

如何在 argparse 不抱怨它不期望的额外参数(我计划稍后添加)的情况下处理前几个参数?

例如,我有一个从命令行获取用户名和密码的脚本,使用它们来访问 API 的可用属性,然后使用该列表来限制第三个的值参数:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('username', help='Your username.')
parser.add_argument('password', help='Your password.')
args = parser.parse_args() # Error here because a third argument exists on the command-line

response = requests.get(
    url='https://api.example.com/properties',
    auth=(args.username, args.password)
)

parser.add_argument(
    'property',
    choices=response.json()['properties'], # Validates the input
    help='The property you want to access.'
)
args = parser.parse_args()

我知道我可以一次添加所有参数,然后自己手动验证第三个参数,但我想知道是否有办法在 argparse 库中以本机方式执行我要求的操作?

parser = argparse.ArgumentParser()
parser.add_argument('username', help='Your username.')
parser.add_argument('password', help='Your password.')
parser.add_argument(
    'property',
    help='The property you want to access.'
)
args = parser.parse_args() 

response = requests.get(
    url='https://api.example.com/properties',
    auth=(args.username, args.password)
)
allowed_properties = response.json()['properties']
if args.property not in allowed_properties:
    parser.error('property not in allowed properties')

choices 不是一个复杂的测试。我建议解析所有输入,然后针对这种特殊情况进行测试。总的来说,我认为给你更好的控制,更好的帮助和错误显示。

parse_known_args 方法很适合学习和偶尔使用,但我认为它不适合这种情况。在 parser.

中嵌入所有参数测试不会获得任何加分