LoginSignup
2
1

More than 1 year has passed since last update.

Pythonのコマンドラインパーサーclickでサブコマンドのサブコマンドを作る

Posted at

Pythonのコマンドラインパーサーclickを使って、サブコマンドのサブコマンドを実装したかったので、雛形を掲載します。

コード

import click


@click.group()  # (1)
@click.pass_context
def aws(ctx):
    pass


# サブコマンド

@aws.group()
@click.pass_context
def ec2(ctx):
    pass


@aws.group()
@click.pass_context
def s3(ctx):
    pass


# ec2サブコマンドのサブコマンド

@ec2.command()
@click.pass_context
def describe_instances(ctx):
    pass


@ec2.command()
def run_instances(ctx):
    pass


# s3サブコマンドのサブコマンド

@s3.command()
@click.pass_context
def cp(ctx):
    pass


@s3.command()
@click.pass_context
def ls(ctx):
    pass


if __name__ == '__main__':
    aws()

実行例

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

Options:
  --help  Show this message and exit.

Commands:
  ec2
  s3

 $ python aws.py ec2
Usage: aws.py ec2 [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  describe-instances
  run-instances

$ python aws.py s3
Usage: aws.py s3 [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  cp
  ls

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1