• 用python -i写交互式shell


    cabinet是公司的一个数据存储服务,需要添加一个shell client,查看数据,做简单操作。

    用python写了一个比想象的简单。代码如下:

    #! /usr/bin/python -i
    # coding: utf-8
    
    
    import sys
    import os
    
    
    dirname = os.path.dirname(sys.argv[0])
    sys.path.append(dirname + '/gen-py') 
    sys.path.append('/usr/lib/python2.7/site-packages')
    from cabinet import CabinetStorage
    from document.ttypes import Document
    from thrift import Thrift
    from thrift.transport import TSocket
    from thrift.transport import TTransport
    from thrift.protocol import TCompactProtocol
    from optparse import OptionParser
    
    
    # avoid UnicodeDecodeError
    reload(sys)
    sys.setdefaultencoding( "utf-8" )
    
    
    try:
      # command line arguments.
      parser = OptionParser(usage="usage: %prog [options]", version="%prog 1.0")
      parser.add_option("-c", "--host", dest = "host", action = "store", default = "127.0.0.1", type = "string", help = "Specify cabinet host.")
      parser.add_option("-p", "--port", dest = "port", action = "store", default = 9090, type = "int", help = "Specify cabinet port.")
      (options, args) = parser.parse_args()
    
    
      # connect to cabinet server.
      transport = TSocket.TSocket(options.host, options.port)  
      transport = TTransport.TBufferedTransport(transport)  
      protocol = TCompactProtocol.TCompactProtocol(transport)  
      client = CabinetStorage.Client(protocol)
      transport.open()
    except Exception as e:
      print e
      os._exit(1)
    
    
    # welcome info.
    print "Cabinet Shell V1.0, Copyright i-MD 2013, All rights reserved."
    print "For usage, invoke help().
    "
    
    
    # main functions.
    def help():
      print "Main functions:"
      print "  get(db, id)"
      print "  set(db, id, val)"
      print "  delete(db, id)"
      print "  unpackDocInfo(docstr)"
      print "  packDocInfo(doc)"
    
    
    def get(db, id):
      return client.Get(db, id) 
    
    
    def set(db, id, val):
      return client.Set(db, id, val)
    
    
    def delete(db, id):
      return client.delete(db, id)
    
    
    def packDocInfo(doc):
      transportOut = TTransport.TMemoryBuffer()
      protocolOut = TCompactProtocol.TCompactProtocol(transportOut)
      doc.write(protocolOut)
      return transportOut.getvalue()
    
    
    def unpackDocInfo(docstr):
      transportIn = TTransport.TMemoryBuffer(docstr)
      protocolIn = TCompactProtocol.TCompactProtocol(transportIn)
      doc = Document()
      doc.read(protocolIn)
      return doc





    不满意的地方是原生的python shell不保存history。

  • 相关阅读:
    msyql多个or,and,
    mysql中 where in 用法详解
    history.back(-1)和history.go(-1)的区别
    经典 mysql 28道题
    企业案例(二):增量恢复案例
    企业案例(一):由于mysql sleep线程过多小故障
    mysql数据库恢复
    binlog介绍
    mysql 数据库备份
    docker入门与实践
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3153248.html
Copyright © 2020-2023  润新知