import cmd
import getopt
import sys
from redis import Redis
from redis.exceptions import ConnectionError
class RedisCli(cmd.Cmd, object):
def __init__(self, host, port):
super(RedisCli, self).__init__()
self.redis = Redis(host=host, port=port)
self.prompt = '(Redis) '
self.intro = '\nConnected to Redis on %s:%d' % (host, port)
for name in dir(self.redis):
if not name.startswith('_'):
attr = getattr(self.redis, name)
if callable(attr):
setattr(self.__class__, 'do_' + name, self._make_cmd(name))
doc = (getattr(attr, '__doc__', '') or '').strip()
if doc:
doc = (' ' * 8) + doc # Fix up the indentation
setattr(self.__class__, 'help_' + name, self._make_help(doc))
try:
# Test the connection. It doesn't matter if 'a' exists or not.
self.redis.get('a')
except ConnectionError, e:
print e
sys.exit(1)
@staticmethod
def _make_cmd(name):
def handler(self, line):
parts = line.split()
try:
print getattr(self.redis, name)(*parts)
except Exception, e:
print 'Error:', e
return handler
@staticmethod
def _make_help(doc):
def help(self):
print doc
return help
def completedefault(self, text, line, start, end):
keys = self.redis.keys(text + '*')
if hasattr(keys, 'split'):
keys = keys.split()
return keys
def do_exit(self, line):
return True
do_EOF = do_exit
def emptyline(self):
pass # By default, cmd repeats the command. We don't want to do that.
if __name__ == '__main__':
opts = dict(getopt.getopt(sys.argv[1:], 'h:p:', ['host=', 'port='])[0])
host = opts.get('-h', None) or opts.get('--host', 'localhost')
port = int(opts.get('-p', None) or opts.get('--port', 56784))
RedisCli(host=host, port=port).cmdloop()
|
Loading...