LoginSignup
21
21

More than 5 years have passed since last update.

Pythonでコマンドライン引数にサブコマンドを指定する

Posted at

はじめに

自分はよくPythonでコマンドラインで動くスクリプトを作るんですが、よく git のようなサブコマンドを作りたいときがあります。

gitの場合

$ git commit -m "test"

この commit がサブコマンド。

このサブコマンドを作ります。

実装

Pythonでコマンド引数をパースしたいときは argparse モジュールを使用します。

15.4. argparse
— コマンドラインオプション、引数、サブコマンドのパーサー —
http://docs.python.jp/2.7/library/argparse.html?highlight=argparse#argparse

通常時は、argparseモジュールから ArgumentParser クラスをimportします。
そしてパーサーを定義し、オプションを追加してく。

通常時 :

normal.py
from argparse import argumentParser

parser = ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

サブコマンドを作成するためには、パーサーをネストすることが必要です。
パーサーの中にまたパーサーを設けることでサブコマンドを設定できるんですね。

subcmd.py
>>> from argparse import ArgumentParser
>>>
>>> # create the top-level parser
>>> parser = ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some arg lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)

parser.add_subparsersメソッドでサブパーサーのラッパーを作り、

subparsers = parser.add_subparsers(help='sub-command help')

ラッパーからサブパーサーを作る。

parser_a = subparsers.add_parser('a', help='a help')

サブパーサーに引数を与えていく。

parser_a.add_argument('bar', type=int, help='bar help')

ちなみに、上記のサンプルの場合、ヘルプメッセージはこのようになる。

usage: PROG [-h] [--foo] {a,b} ...

positional arguments:
{a,b}       sub-command help
a         a help
b         b help

optional arguments:
-h, --help  show this help message and exit
--foo       foo help

これで、サブコマンドの作成が可能だ。

21
21
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
21
21