python-3.x - Pickle data was truncated when importing more than one list
问题描述
I'm trying to build a client-server application for a college project, and the main goal is to have a client machine make a request to get some information from a server machine, such as cpu usage, memory usage, files and directories and such, and send them back to the client machine to read (I'm also presenting these information graphically in pygame). Whenever I try to use pickle.load more than once, I get this error on the client side:
Traceback (most recent call last):
File "(...)", line 23, in <module>
lista = pickle.loads(caminho)
_pickle.UnpicklingError: pickle data was truncated
Does anyone know to use load information from server more than once? I'd really appreciate any kind of help!
Server side:
import socket, psutil, pickle, os, time, datetime, cpuinfo
def mostra_uso_cpu_e_ram(socket_cliente):
info1 =('Usuario solicitou Informações de uso de processamento e Memória')
resposta = []
resposta.append(psutil.cpu_percent())
resposta.append(cpuinfo.get_cpu_info()['brand'])
resposta.append(cpuinfo.get_cpu_info()['arch'])
resposta.append(cpuinfo.get_cpu_info()['bits'])
resposta.append(cpuinfo.get_cpu_info()['hz_actual'])
resposta.append(psutil.cpu_freq()[0])
resposta.append(psutil.disk_usage('/')[3])
mem = psutil.virtual_memory()
mem_percent = mem.used/mem.total
resposta.append(mem_percent)
bytes_resp = pickle.dumps(resposta)
socket_cliente.send(bytes_resp)
print(info1)
def arquivos_diretorios(socket_cliente):
info2 = ('\nUsuario solicitou Informações sobre arquivos e diretórios')
info2 += ('\n\n-------------------------------------------------------\n\n INFORMAÇÕES SOBRE DIRETÓRIOS E ARQUIVOS\n')
socket_cliente.send(info2.encode('utf-8'))
lista_send = []
caminho = os.getcwd()
lista_send.append(caminho)
caminho = pickle.dumps(lista_send)
socket_cliente.send(caminho)
lista_arquivos = []
for a in os.listdir("."):
if os.path.isdir(a):
pathname = 'd %s' % a
lista_arquivos.append(pathname)
statinfo = os.stat(a)
data_criacao = datetime.datetime.fromtimestamp(statinfo.st_ctime)
data_acesso = datetime.datetime.fromtimestamp(statinfo.st_atime)
data_modificacao = datetime.datetime.fromtimestamp(statinfo.st_mtime)
size = os.path.getsize(a)
criacao = 'Data de Criação: {}'.format(data_criacao)
lista_arquivos.append(criacao)
acesso = 'Data do Acesso mais recente: {}'.format(data_acesso)
lista_arquivos.append(acesso)
modificacao = 'Data da última modificação: {}'.format(data_modificacao)
lista_arquivos.append(modificacao)
tamanho = 'Tamanho do diretório em bytes: {}'.format(size)
lista_arquivos.append(tamanho)
elif os.path.isfile(a):
pathname = '- %s' % a
lista_arquivos.append(pathname)
statinfo = os.stat(a)
data_criacao = datetime.datetime.fromtimestamp(statinfo.st_ctime)
data_acesso = datetime.datetime.fromtimestamp(statinfo.st_atime)
data_modificacao = datetime.datetime.fromtimestamp(statinfo.st_mtime)
size = statinfo.st_size
criacao = 'Data de Criação: {}'.format(data_criacao)
lista_arquivos.append(criacao)
acesso = 'Data do Acesso mais recente: {}'.format(data_acesso)
lista_arquivos.append(acesso)
modificacao = 'Data da última modificação: {}'.format(data_modificacao)
lista_arquivos.append(modificacao)
tamanho = 'Tamanho do arquivo em bytes: {}'.format(size)
lista_arquivos.append(tamanho)
arq_dir = pickle.dumps(lista_arquivos)
socket_cliente.send(arq_dir)
def processos_ativos(socket_cliente):
info3 = ('\nUsuario solicitou Informações sobre processos ativos')
info3 += ('\n\n-------------------------------------------------------\n\n INFORMAÇÕES SOBRE PROCESSOS EM ANDAMENTO\n')
info3 += ('\n\n*** Lista de processos em andamento no servidor ***\n\n')
socket_cliente.send(info3.encode('utf-8'))
listOfProcessNames = []
for proc in psutil.process_iter():
pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent'])
listOfProcessNames.append(pInfoDict)
proc_info = pickle.dumps(listOfProcessNames)
socket_cliente.send(proc_info)
def informacoes_redes(socket_cliente):
info4 = ('\nUsuario solicitou Informações sobre Rede')
info4 += ('\n\n-------------------------------------------------------\n\n INFORMAÇÕES SOBRE REDE\n')
socket_cliente.send(info4.encode('utf-8'))
af_map = {
socket.AF_INET: 'IPv4',
socket.AF_INET6: 'IPv6',
psutil.AF_LINK: 'MAC',
}
stats = psutil.net_if_stats()
io_counters = psutil.net_io_counters(pernic=True)
lista_redes = []
for nic, addrs in psutil.net_if_addrs().items():
rede = '%s:' % (nic)
lista_redes.append(rede)
for addr in addrs:
rede1 = ' %-4s' % af_map.get(addr.family, addr.family)
lista_redes.append(rede1)
rede2 = ' address : %s' % addr.address
lista_redes.append(rede2)
if addr.broadcast:
rede3 = ' broadcast : %s' % addr.broadcast
lista_redes.append(rede3)
if addr.netmask:
rede4 = ' netmask : %s' % addr.netmask
lista_redes.append(rede4)
if addr.ptp:
rede5 = ' p2p : %s' % addr.ptp
lista_redes.append(rede5)
#print("")
rede_info = pickle.dumps(lista_redes)
socket_cliente.send(rede_info)
def sair_da_conexao(socket_cliente):
info = ('Conexão Encerrada!')
socket_cliente.send(info.encode('utf-8'))
print("Fechando Conexão...")
socket_cliente.close()
socket_servidor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
porta = 9999
socket_servidor.bind((host, porta))
socket_servidor.listen()
print("Servidor", host, "esperando conexão na porta", porta)
(socket_cliente,addr) = socket_servidor.accept()
print("Conectado a:", str(addr))
while True:
mostra_uso_cpu_e_ram(socket_cliente)
arquivos_diretorios(socket_cliente)
processos_ativos(socket_cliente)
informacoes_redes(socket_cliente)
sair_da_conexao(socket_cliente)
Client side:
import socket, time, pickle
import pygame
def imprime(l):
texto = ''
for i in l:
texto = texto + '\n' + '{:>20}'.format(i)
print(texto)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 9999))
bytes_resp = s.recv(1024)
lista = pickle.loads(bytes_resp)
memoria = imprime(lista)
info2 = s.recv(4000)
caminho = s.recv(4000)
arq_dir = s.recv(1000000)
lista = pickle.loads(caminho)
files_info = pickle.loads(arq_dir)
def display_slide():
tela1 = True
while tela1:
tela.fill([0, 0, 0])
texto1 = font.render('MENU', True, verde, preto)
textoRect1 = texto1.get_rect()
textoRect1.topleft=[100,25]
tela.blit(texto1, textoRect1)
textoc = font.render('1 - Uso de Processamento e Memória ', True, verde, preto)
textoRectc = textoc.get_rect()
textoRectc.topleft=[10,100]
tela.blit(textoc, textoRectc)
texto2 = font.render('2 - Arquivos e Diretórios ', True, verde, preto)
textoRect2 = texto2.get_rect()
textoRect2.topleft=[10,150]
tela.blit(texto2, textoRect2)
texto3 = font.render('3 - Processos Ativos: ', True, verde, preto)
textoRect3 = texto3.get_rect()
textoRect3.topleft=[10,200]
tela.blit(texto3, textoRect3)
texto4 = font.render('4 - Redes ', True, verde, preto)
textoRect4 = texto4.get_rect()
textoRect4.topleft=[10,250]
tela.blit(texto4, textoRect4)
texto5 = font.render('5 - Sair ', True, verde, preto)
textoRect5 = texto5.get_rect()
textoRect5.topleft=[10,300]
tela.blit(texto5, textoRect5)
texto6 = font.render('Selecione uma das opções do menu ou pressione seta para a direita para navegar ', True, verde, preto)
textoRect6 = texto6.get_rect()
textoRect6.topleft=[10,350]
tela.blit(texto6, textoRect6)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
tela1 = False
tela2 = True
else:
if event.key == pygame.K_1:
tela1 = False
tela2 = True
while tela2:
tela.fill([0, 0, 0])
texto1 = font.render('Informações: '+str(memoria), True, verde, preto)
textoRect1 = texto1.get_rect()
textoRect1.topleft=[10,5]
tela.blit(texto1, textoRect1)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
tela2 = False
tela1 = True
#elif event.key == pygame.K_RIGHT:
#tela2 = False
#tela3 = True
pygame.init()
largura_tela = 800
altura_tela = 800
tela = pygame.display.set_mode((largura_tela, altura_tela))
background = pygame.Surface(tela.get_size())
tela.blit(background, (0,0))
pygame.display.set_caption('Monitoramento e Análise do Sistema')
tela.fill([0, 0, 0])
verde = (0, 255, 0)
preto = (0, 0, 0)
cinza = (128, 128, 128, 255)
font = pygame.font.Font(None, 24)
terminou = False
while not terminou:
display_slide()
pygame.display.update()
pygame.display.quit()
pygame.quit()
解决方案
没关系,我的错误,发现我使用了同一个变量“lista”两次。一旦我把它从代码中拿出来,它就起作用了
推荐阅读
- r - ggplot小提琴图,按组指定不同的颜色?
- python - 如何设置 Django `Debugger` 时间?
- azure - Azure 容器实例一次又一次地失败
- vb.net - PNG文件的每像素比特成本
- html - 为什么填充和边距不起作用?
- javascript - Javascript,将地址字符串传递给 MapQuest API 不起作用
- javascript - 实现无节点的工作箱
- php - 存储过程计算每个部门每天 10% 的休假配额
- iis - 应用程序请求路由:为什么有些网站返回 HTTP 404 而有些却没有?
- python - 启动时出现 Django runserver 错误