import socket
import os
s = socket.socket()
connection_host = input("Please input redis host[localhost]:" )
if not connection_host:
connection_host = "localhost"
connection_port = input("Please input redis port[6379]:")
if not connection_port:
connection_port = '6379'
connection_port = int(connection_port)
s.connect((connection_host, connection_port))
def recv_not_enter(sc):
result = ''
while True:
char = sc.recv(1).decode()
if char == '\r':
char2 = sc.recv(1).decode()
if char2 == '\n':
return result
else:
result = result + char + char2
else:
result = result + char
while True:
command = input("Redis>")
commmand = command.strip()
if command:
if command.startswith("system "):
system_command = command[7:]
os.system(system_command)
else:
s.send((command+"\r\n").encode("utf-8"))
flag = s.recv(1).decode()
if flag == '+':
print(recv_not_enter(s))
elif flag == '-':
print(recv_not_enter(s))
elif flag == '$':
byte_size = int(recv_not_enter(s))
print(s.recv(byte_size).decode())
s.recv(2)
Python实现Redis客户端
最新推荐文章于 2024-08-22 20:00:34 发布
本文提供了一个使用Python的socket库与Redis服务器进行交互的示例代码。通过该脚本,用户可以输入Redis命令并接收响应,同时支持执行系统命令。代码展示了如何连接到Redis服务器、发送命令以及解析不同类型的消息。
摘要由CSDN通过智能技术生成