Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

ClickをつかってPython製CLIツールをスマートにする その5:gitのような子コマンドをもつもの

gitのように、ネスト構造をもつコマンドを作る方法です。

実際のところ

コマンドのヘルプ文は長コメントで入れます

import click

#親コマンド
@click.group()
def cli():
    pass

#子コマンド。cli()という関数に紐づくので@cli以下に続ける
@cli.command()
def init():
    """
      init command
    """
    click.echo('Initialized the database')

@cli.command()
def drop():
    """
      drop command
    """
    click.echo('Dropped the database')


if __name__ == '__main__':
   cli()

使ってみる

親コマンドをそのまま入れると、子コマンドの説明が入ります

$ python sample_click_nest.py
Usage: sample_click_nest.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  drop  drop command
  init  init command

子コマンドは、通常のコマンドと同じですね・

$ python sample_click_nest.py init
Initialized the database


$ python sample_click_nest.py drop
Dropped the database

ヘルプコマンドも有効

$ python sample_click_nest.py drop --help
Usage: sample_click_nest.py drop [OPTIONS]

  drop command

Options:
  --help  Show this message and exit.