问题
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}/
)
I tried
p.add_argument('hex', type=str, nargs="[a-f0-9A-F]{32}")
without success
回答1:
This is what the type kwarg is used for: it can take any callable that takes a single string argument and returns the converted value.
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])
来源:https://stackoverflow.com/questions/41881002/python-argparse-regex-expression