[Click] 1. Click 소개

LULLU·2022년 9월 5일
0
post-thumbnail

TL;DR

  • click은 python method를 command로 만들어주는 package이다.

What is click?

Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”

  • 최소한의 노력으로 멋진 CLI를 만들자는 철학을 가진다.

Simple example

import click

@click.command()
@click.option('--count', default=1, help='Count for Hello world')
def hello(count):
		"""Simple program that print "Hello World!" COUNT times."""
    for x in range(count):
        click.echo('Hello World!')

if __name__ == '__main__':
    hello()

$ python hello.py --count=3
Hello World!
Hello World!
Hello World!
  • decorator를 사용해 간단하게 method를 command화 할 수 있다.
  • option, argument도 간편하게 지정할 수 있다.

Auto-generate Help Page

$ python hello.py --help
Usage: hello.py [OPTIONS]

  Simple program that print "Hello World!" COUNT times.

Options:
  --count INTEGER  Count for Hello world
  --help           Show this message and exit.

Group

@click.group()
@click.option('--debug/--no-debug', default=False)
def cli(debug):
    click.echo('Debug mode is %s' % ('on' if debug else 'off'))

@cli.command(help="Check packages in venv")
@click.argument("venv_type", type=click.Choice(["code", "layer"]))
def checkpkgs(venv_type):
    ...
    
@cli.command(help="Install packages in venv (default: in layer)",)
@click.argument("venv_type", type=click.Choice(["code", "layer"]), default="layer")
def installpkgs(venv_type):
    ...
  • 여러 subcommand들을 Group으로 묶을 수 있다.
$ layer_manage.py
Usage: layer_manage.py [OPTIONS] COMMAND [ARGS]...

Options:
  --debug / --no-debug
  --help                Show this message and exit.

Commands:
  checkpkgs
  installpkgs
  • help 페이지에 subcommands를 정리해서 보여준다.
  • Callback Invocation
    • @click.group()으로 decorate된 method는 subcommand가 호출될 때에만 method 내부가 실행된다.

0개의 댓글