Python argparse 正则表达式

Python argparse regex expression

是否可以使用正则表达式来解析参数?例如,我想接受一个参数,只要它是一个 32 长度的十六进制(即匹配 /[a-f0-9A-F]{32}/

我试过了

p.add_argument('hex', type=str, nargs="[a-f0-9A-F]{32}")

没有成功

type 关键字参数可以接受任何接受单个字符串参数和 returns 转换值的可调用对象。如果可调用对象引发 argparse.ArgumentTypeErrorTypeErrorValueError,则会捕获异常并显示格式正确的错误消息。

import argparse
import re 
from uuid import uuid4

def my_regex_type(arg_value, pat=re.compile(r"^[a-f0-9A-F]{32}$")):
    if not pat.match(arg_value):
        raise argparse.ArgumentTypeError
    return arg_value

parser = argparse.ArgumentParser()
parser.add_argument('hex', type=my_regex_type)

args = parser.parse_args([uuid4().hex])