用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().\n" # 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。

上一篇:Kindle 电子书相关的工具软件【转】


下一篇:电子书及阅读器Demo