Python Click CLI: Validate and Modify Arguments

July 29, 2019

Click arguments validation and modify arguments.

  • Symbol must be BTCUSDT, ETHUSDT, BTCETH as per this rule.
  • Split symbol from BTCUSDT into BTC and USDT.
import click
import re

def validate_symbol(ctx, param, value):
    m = re.search(r'^(\w+)(BTC|ETH|BNB|USDT|PAX|TUSD|USDC)$', value)
    if m:
        c1_symbol = m.group(1)
        c2_symbol = m.group(2)
        return (c1_symbol, c2_symbol)
    else:
        raise click.BadParameter('Invalid symbol')

@cli.command()
@click.option('--symbol', callback=validate_symbol, required=True)
def get_price(symbol):
    c1_symbol, c2_symbol = symbol
    symbol = ''.join(symbol)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.