-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·78 lines (64 loc) · 1.95 KB
/
cli.py
File metadata and controls
executable file
·78 lines (64 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: UTF-8 -*-
"""
Command Line Interface Sample.
"""
import argparse
from pprint import pprint
class Command(object):
"""
"""
def __init__(self, args):
# Get argument parse options
self.args = args
def create(self):
id = self.args.id
amount = self.args.amount
if id == 0:
raise Exception("--id is required.")
if amount == 0:
raise Exception("--amount is required.")
txt = 'create(id={}, amount={})'.format(id, amount)
print(txt)
def show(self):
id = self.args.id
if id == 0:
raise Exception("--id is required.")
txt = 'show(id={})'.format(id)
print(txt)
def update(self):
id = self.args.id
amount = self.args.amount
if id == 0:
raise Exception("--id is required.")
if amount == 0:
raise Exception("--amount is required.")
txt = 'update(id={}, amount={})'.format(id, amount)
print(txt)
def delete(self):
id = self.args.id
if id == 0:
raise Exception("--id is required.")
txt = 'delete(id={})'.format(id)
print(txt)
def run(args):
# クラスメソッドをコール
try:
c = Command(args)
getattr(c, args.command)()
except Exception as e:
print(e)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='コマンドラインインターフェースのサンプルコード。')
# 主要コマンド
command_list = ['create', 'show', 'update', 'delete']
command_help = 'create: データを作成する'
command_help += ' | show: データを確認する'
command_help += ' | update: データを更新する'
command_help += ' | delete: データを削除する'
parser.add_argument('command', type=str, choices=command_list, help=command_help)
# コマンドオプション指定
parser.add_argument('--id', type=int, help='ID指定 $ python cli.py show --id 1', default=0)
parser.add_argument('--amount', type=float, help='数量を指定する $ python cli.py create --id 1 --amount 100.0', default=0)
args = parser.parse_args()
# Get start
run(args)