导入多个列表时,泡菜数据被截断

问题描述

我正在尝试为一个大学项目构建客户端-服务器应用程序,其主要目标是让客户端计算机请求从服务器计算机获取一些信息,例如cpu使用率,内存使用率,文件和目录等,然后将它们发送回客户端计算机以进行读取(我也在pygame中以图形方式呈现了这些信息)。 每当我尝试多次使用pickle.load时,都会在客户端收到此错误:

Traceback (most recent call last):
  File "(...)",line 23,in <module>
    lista = pickle.loads(caminho)
_pickle.UnpicklingError: pickle data was truncated

有人知道多次使用服务器的负载信息吗?我真的很感谢任何帮助!

服务器端:

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)

客户端:

import socket,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])
    
        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 ',preto)
        textoRectc = textoc.get_rect()
        textoRectc.topleft=[10,100]
        tela.blit(textoc,textoRectc)
        
        texto2 = font.render('2 - Arquivos e Diretórios ',preto)
        textoRect2 = texto2.get_rect()
        textoRect2.topleft=[10,150]
        tela.blit(texto2,textoRect2)
        
        texto3 = font.render('3 - Processos Ativos: ',preto)
        textoRect3 = texto3.get_rect()
        textoRect3.topleft=[10,200]
        tela.blit(texto3,textoRect3)
        
        texto4 = font.render('4 - Redes ',preto)
        textoRect4 = texto4.get_rect()
        textoRect4.topleft=[10,250]
        tela.blit(texto4,textoRect4)
        
        texto5 = font.render('5 - Sair ',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 ',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])
        
        texto1 = font.render('Informações: '+str(memoria),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])

verde = (0,255,0)
preto = (0,0)
cinza = (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”。一旦我从代码中删除了它,它就起作用了

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...