Using Regex to validate a parameter using Python library click?
Asked Answered
D

1

6

I'm using click for parsing command line argument https://click.palletsprojects.com/en/7.x/

import click
@click.option('-n', '--name', required=True, type=str, help='...')
def create(name: str):

I want to use regular express to make sure the name matching a particular pattern. How to do it using click?

Dictatorship answered 12/4, 2021 at 20:46 Comment(0)
D
8

Use callback.

def open_url(ctx, param, value):
    if re.match('...', value):
        return value
    else:
        raise click.BadParameter('.....')

@click.command()
@click.option('--url', callback=open_url)
def cli(url, fp=None):
Dictatorship answered 14/4, 2021 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.