查看memcache所有key的小程序
本地开发过程中经常要查看内容写没写到memcache中,一般看一下memcache中有没有想对应的key就好了,懒得用telnet连接memcache,自带的memcached-tool输出又不怎么方便阅读,so 写了一个简单的查看memcache中key的python小程序
1 # /usr/bin/env python
2 # -*- coding: utf-8 -*
3 import socket
4 import re
5
6 class MemcacheServer(object):
7 def __init__(self):
8 self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
9
10 def connect(self, host=None, port=None):
11 self.host = host
12 self.port = port
13 try:
14 self.server.connect((host, port))
15 except:
16 print "connect error ......"
17
18
19 def send(self, msg):
20 self.server.send(msg)
21
22 def get_msg(self):
23 buf_len = 1024
24 msg = u""
25 while True:
26 buf = self.server.recv(buf_len)
27 msg += buf
28 if len(buf)!=buf_len:
29 break
30 return msg
31
32 if __name__ == "__main__":
33 ms = MemcacheServer()
34 ms.connect("127.0.0.1", 11211)
35
36 items = {}
37 totalitems = 0
38 ms.send("stats items\r\n")
39 for line in ms.get_msg().splitlines():
40 match = re.search(u"^STAT items:(\d*):number (\d*)", line)
41 if match:
42 i, j = match.groups()
43 items[int(i)] = int(j)
44 totalitems += int(j)
45
46 for buckets in sorted(items.keys()):
47 ms.send("stats cachedump %d %d\r\n" % (buckets, items[buckets]))
48 for line in ms.get_msg().splitlines():
49 match = re.search(u"^ITEM (\S+) \[.* (\d+) s\]", line)
50 if match:
51 print match.groups()[0]