# -*- coding: utf-8 -*- #!/usr/bin/env python """ TODO 利用parse 和 string formatting 以及 读取配置文件json 或者环境变量 """ import subprocess import click import delegator @click.group def cli(): pass class Command(object): def __init__(self, executor): self._executor = executor def build(self, **options): prefix = lambda _ : '-' if len(_) == 1 else '--' return [self._executor] + [ prefix(k) + ' '.join((k, v)) for k, v in options] def run(self, **options): actions = self.build(**options) return subprocess.check_output(actions).decode('utf-8') class ShellCommand(Command): def __init__(self, template): self.template = template def run(self, **options): return delegator.run(self.template.format_map(options)) mongodump = ShellCommand('mongodump -u {user} -p {password} --authenticationDatabase {authdb} --host {host} --port {port} -d {destDB} -o {destDir}') mongorestore = ShellCommand('mongorestore -u {user} -p {password} --authenticationDatabase {authdb} --host {host} --port {port} -d {destDB} --dir {destDir}') @cli.command() @click.option('-f','--filepath', prompt=u'请输入要转换的表格文件路径') @click.option('-s','--sync', prompt=u'同步') @click.option('-c','--config', prompt=u'配置') def mongo(): restore = Command(executor='mongorestore') dump = Command(executor='mongodump') ### Memcached def backup_memcached(host, port, toFileName): """ memcached-tool 127.0.0.1:11211 dump > 11211data memcached-tool 127.0.0.1:11212 dump > 11212data """ delegator.run('memcached-tool {host}:{port} dump > {toFileName}'\ .format(host=host, port=port, toFileName=toFileName)) def restore_memcached(host, port, fromFileName): """ nc localhost 11211 < 11211data nc localhost 11212 < 11212data """ delegator.run('nc {host} {port} < {fromFileName}'.format(host=host, port=port, fromFileName=fromFileName))