zoukankan      html  css  js  c++  java
  • 用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。

  • 相关阅读:
    实现 (5).add(3).minus(2) 功能
    vue兄弟组件传值的三种方法
    Web渗透测试思路整理
    PHP代码审计基础
    简单易用,用Powershell劫持Windows系统快捷键
    javascript脚本混淆
    秒杀系统架构优化思路
    什么是OOP
    一分钟了解负载均衡的一切
    MVC
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3153248.html
Copyright © 2011-2022 走看看