Python argparse 正则表达式 [英] Python argparse regex expression
本文介绍了Python argparse 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用正则表达式来解析参数?例如,我想接受一个参数,只要它是一个 32 长度的十六进制(即匹配 /[a-f0-9A-F]{32}/
)
Is it possible to use a regex expression for parsing an argument? For example, I want to accept an argument if only it is a 32 length hex (i.e. matches /[a-f0-9A-F]{32}/
)
我试过了
p.add_argument('hex', type=str, nargs="[a-f0-9A-F]{32}")
没有成功
推荐答案
type
关键字参数可以接受任何接受单个字符串参数并返回转换后的值的可调用对象.如果可调用对象引发 argparse.ArgumentTypeError
、TypeError
或 ValueError
,则会捕获异常并显示格式良好的错误消息.
The type
keyword argument can take any callable that accepts a single string argument and returns the converted value. If the callable raises argparse.ArgumentTypeError
, TypeError
, or ValueError
, the exception is caught and a nicely formatted error message is displayed.
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])
这篇关于Python argparse 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文