Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse regex expression

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

like image 396
Kousha Avatar asked Jan 26 '17 19:01

Kousha


People also ask

How do you add arguments in Argparse?

To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required . The name is exactly what it sounds like — the name of the command line field.

What does Argparse ArgumentParser () do?

>>> parser = argparse. ArgumentParser(description='Process some integers. ') The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.

What is Metavar in Argparse Python?

Metavar: It provides a different name for optional argument in help messages.


1 Answers

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("invalid value")
    return arg_value

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

args = parser.parse_args([uuid4().hex])
like image 94
wim Avatar answered Oct 20 '22 23:10

wim