当前位置:论坛首页 > Linux面板 > 求助

【已解答】求助宝塔的python项目运行后CPU耗费严重

发表在 Linux面板2020-10-29 19:18 [复制链接] 1 1584

  1. #!/usr/bin/env Python
  2. # coding=utf-8
  3. import socket  # 导入 socket 模块
  4. import struct
  5. from threading import Thread
  6. import time
  7. import ast
  8. import user
  9. import company
  10. import crew
  11. import pymysql
  12. import equipment
  13. import overhaul
  14. import config
  15. import common
  16. import os
  17. import takejudge
  18. from base import Protocol
  19. import json
  20. import metal.standingbook as standingbook
  21. import metal.MetallicMaterials as metallic
  22. import metal.MetalPlan as MetalPlan
  23. import filemanage




  24. ADDRESS = ('', 7891)  # 绑定地址
  25. FILEADDRESS = ('', 7890)  # 绑定服务器接收文件的IP地址
  26. g_socket_server = None  # 负责监听的socket
  27. file_socket_server = None  # 负责监听file的socket
  28. g_conn_pool = []  # 连接池
  29. gfile_conn_pool = []  # 连接池
  30. # BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  31. BASE_DIR = "/data/"
  32. ##print('basedir:',BASE_DIR)

  33. '''
  34. 接收数据格式:
  35. 判断方式+

  36. '''

  37. def init():
  38.     """
  39.     初始化服务端
  40.     """
  41.     global g_socket_server,file_socket_server
  42.     g_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建 socket 对象
  43.     g_socket_server.bind(ADDRESS)
  44.     g_socket_server.listen(128)  # 最大等待数(有很多人理解为最大连接数,其实是错误的)
  45.     print("服务端已启动,等待客户端连接...")
  46.     '''接收文件的服务器'''
  47.     file_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建 socket 对象
  48.     file_socket_server.bind(FILEADDRESS)
  49.     file_socket_server.listen(128)  # 最大等待数(有很多人理解为最大连接数,其实是错误的)
  50.     ##print("服务端已启动,等待客户端连接...")


  51. def accept_client():
  52.     """
  53.     接收新连接
  54.     """
  55.     while True:
  56.         client, _ = g_socket_server.accept()  # 阻塞,等待客户端连接
  57.         ##print(client)
  58.         # 加入连接池
  59.         g_conn_pool.append(client)

  60.         # 给每个客户端创建一个独立的线程进行管理
  61.         thread = Thread(target=message_handle, args=(client,))
  62.         # 设置成守护线程
  63.         thread.setDaemon(True)
  64.         thread.start()

  65. def accept_file_client():
  66.     """
  67.     接收新连接
  68.     """
  69.     while True:
  70.         clientfile, _ = file_socket_server.accept()  # 阻塞,等待客户端连接
  71.         ##print(client)
  72.         # 加入连接池

  73.         # 给每个客户端创建一个独立的线程进行管理
  74.         thread = Thread(target=file_handle, args=(clientfile,))
  75.         # 设置成守护线程
  76.         thread.setDaemon(True)
  77.         thread.start()
  78. def pck_handler(client,recvtext):
  79.     """
  80.     解析数据包
  81.     """

  82.     # 正常数据包定义
  83.     ##print(typesendtext',type(recvtext),recvtext)
  84.     print("第一次",recvtext)
  85.     b2 = recvtext.decode('utf8')
  86.     print(recvtext.decode("utf-8").encode("GBK") )

  87.     ##print("特殊字符转义前:!",b2)
  88.     # body = pymysql.escape_string(b2)
  89.     ##print("特殊字符转义后:!",body)
  90.     user_dict = ast.literal_eval(b2)

  91.     print('user_dist',user_dict)
  92.     '''对内含特殊字符的内容进行批量转义开始'''
  93.     for n in user_dict:
  94.         if type(user_dict[n]) == str:
  95.             ##print(n, pymysql.escape_string(user_dict[n]))
  96.             user_dict[n] = pymysql.escape_string(user_dict[n])
  97.         else:
  98.             pass
  99.             ##print(n, 'is not str')
  100.     '''对内含特殊字符的内容进行批量转义结束'''
  101.     ##print(user_dict['juage'])
  102.     print(user_dict)

  103.     # myddd =  str(sendtext, encoding = "utf8")
  104.     ##print(myddd,type(myddd))

  105.     if user_dict['juage'] == 'common':
  106.         ##print(当前在线人数:',len(g_conn_pool))
  107.         if user_dict['name'] == 'getmysqltable':
  108.             #'获得表结构')
  109.             result = common.getmysqltable(user_dict)
  110.             #('result',result)
  111.         elif user_dict['name'] == 'save_tablewidgetdata':
  112.             ##print(获取指定表内的1条数据')
  113.             result = common.save_tablewidgetdata(user_dict)
  114.             ##print(result',result)

  115.     elif user_dict['juage'] == 'user':
  116.         ##print(juage1')
  117.         if user_dict['name'] == 'register':
  118.             ##print(juage2')
  119.             result = user.UserRegister(user_dict)
  120.             ##print(result',result)
  121.         elif user_dict['name'] == 'createsonuser':
  122.             ##print(checklogin')
  123.             result = user.createsonuser(user_dict)

  124.     send_text(client,str(result))

  125. def send_text(client,senddata):
  126.     ##print('准备发送:',client,"\n",senddata)
  127.     ver = 1

  128.     #
  129.     try:
  130.         body = json.dumps(senddata)#方法1
  131.     except:
  132.         body = str(senddata)  # 方法2,强制
  133.     ##print(body,type(body))
  134.     ##print(len(body))
  135.     ##print(body.__len__())
  136.     cmd = 101
  137.     header = [ver, body.__len__(), cmd]
  138.     ##print('header',header)
  139.     headPack = struct.pack("!3I", *header)
  140.     ##print('headPack',headPack)

  141.     sendData1 = headPack + body.encode()
  142.     ##print('sendData1',sendData1)
  143.     client.send(sendData1)
  144.     client.close()
  145.     # # 删除连接
  146.     g_conn_pool.remove(client)


  147. def dataHandle(client,headPack, bytes):
  148.     # 切割数据包
  149.     while True:
  150.         # 读取包长度
  151.         length_pck = int.from_bytes(bytes[:4], byteorder='little')
  152.         ##print(包长度', length_pck)
  153.         # 截取封包
  154.         pck = bytes[4:4 + length_pck]
  155.         # 删除已经读取的字节
  156.         bytes = bytes[4 + length_pck:]
  157.         ##print(pck, bytes, '把封包交给处理函数')

  158.         # 把封包交给处理函数
  159.         pck_handler(pck, client)
  160.         ##print(2')
  161.         # 如果bytes没数据了,就跳出循环
  162.         if len(bytes) == 0:
  163.             break
  164.         ##print("客户端消息:", bytes.decode(encoding="utf8"))


  165. def message_handle(client):#用于接收服务器发过来的分包数据
  166.     """
  167.     消息处理
  168.     """
  169.     # FIFO消息队列
  170.     ##print("FIFO消息队列")
  171.     dataBuffer = bytes()

  172.     ##print("databuffer:",type(dataBuffer))
  173.     # 自定义消息头的长度
  174.     headerSize = 12

  175.     # 定义数据包的个数
  176.     sn = 0
  177.     # client.sendall("lianjiechenggong!".encode(encoding='utf-8'))
  178.     while True:
  179.         try:
  180.             data = client.recv(1024)
  181.             len(data)

  182.             if data:
  183.                 # 把数据存入缓冲区,类似于push数据
  184.                 dataBuffer += data
  185.                 while True:
  186.                     if len(dataBuffer) < headerSize:
  187.                         ##print("数据包(%s Byte)小于消息头部长度,跳出小循环" % len(dataBuffer))
  188.                         break

  189.                     # 读取包头
  190.                     # struct中:!代表Network order,3I代表3个unsigned int数据
  191.                     headPack = struct.unpack('!3I', dataBuffer[:headerSize])
  192.                     bodySize = headPack[1]

  193.                     # 分包情况处理,跳出函数继续接收数据
  194.                     if len(dataBuffer) < headerSize + bodySize:
  195.                         ##print("数据包(%s Byte)不完整(总共%s Byte),跳出小循环" % (len(dataBuffer), headerSize + bodySize))
  196.                         break

  197.                     # 读取消息正文的内容
  198.                     body = dataBuffer[headerSize:headerSize + bodySize]

  199.                     # 数据处理
  200.                     ##print("接收到的完整信息:!",body)
  201.                     ##print("接收到的完整type:!",type(body))

  202.                     # body = pymysql.escape_string(body)
  203.                     ##print("特殊字符转义后:!",body)

  204.                     pck_handler(client,body)

  205.                     # 数据出列
  206.                     dataBuffer = dataBuffer[headerSize + bodySize:]  # 获取下一个数据包,类似于把数据pop出


  207.         except Exception as e:  # 意外掉线
  208.             ##print("---------------------------")
  209.             ##print("客户端断开了。" )
  210.             # client.close()
  211.             # 删除连接
  212.             # g_conn_pool.remove(client)


  213.             break


  214. def file_handle(fileclient):#用于接收服务器发过来的文件分包数据
  215.     """
  216.     上传文件处理
  217.     """
  218.     while True:
  219.         data = ''
  220.         data = fileclient.recv(1024)       #开始接收
  221.         ##print(data)
  222.         ##print(str(data,'utf8'))
  223.         file_size,savepath,newname = str(data,'utf8').split('|')
  224.         # path = os.path.join(BASE_DIR,'yuan',filename)
  225.         # 判断文件夹是否存在,不存在,就创建
  226.         path = os.path.join(BASE_DIR,savepath)
  227.         if os.path.exists(path) == False:  #
  228.             os.makedirs(path)

  229.         path = os.path.join(BASE_DIR, savepath, newname)
  230.         ##print(path)
  231.         file_size = int(file_size)
  232.         ##print(file_size,savepath,newname)
  233.         f = open(path,'ab')
  234.         has_receive = 0
  235.         while has_receive != file_size:
  236.             data = fileclient.recv(1024)
  237.             f.write(data)
  238.             has_receive += len(data)
  239.             ##print('接收数据',has_receive,file_size)
  240.         ##print('接收数据完成', has_receive, file_size)
  241.         f.close()
  242.         break
  243.     ##print('关闭当前连接')
  244.     fileclient.close()


  245. if __name__ == '__main__':
  246.     init()
  247.     # 新开一个线程,用于接收新连接
  248.     thread = Thread(target=accept_client)
  249.     thread.setDaemon(True)
  250.     thread.start()
  251.     threadfile = Thread(target=accept_file_client)
  252.     threadfile.setDaemon(True)
  253.     threadfile.start()
  254.     config.mysql
  255.     while True:
  256.         
  257.         if len(g_conn_pool)==0:
  258.             time.sleep(5)
  259.             

  260.         for i in g_conn_pool:
  261.             ##print(i)

  262.             time.sleep(5)

复制代码

求助:python在宝塔管理项目运行时CPU占用严重。
以前在windows系统下运行挺好,现在将python程序通过centos的宝塔面板python管理项目运行,CPU占用严重。python版本:3.7.8
框架:python
启动方式:python

使用道具 举报 只看该作者 回复
发表于 2020-10-29 20:16:31 | 显示全部楼层
您好,cpu占用高时,ssh内执行以下命令排查分析
  1. yum -y install htop && htop
复制代码

如果确定是这个项目占用,建议脚本再细品下
使用道具 举报 回复 支持 反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

企业版年付运维跟进群

普通问题处理

论坛响应时间:72小时

问题处理方式:排队(仅解答)

工作时间:白班:9:00 - 18:00

紧急问题处理

论坛响应时间:10分钟

问题处理方式:1对1处理(优先)

工作时间:白班:9:00 - 18:00

工作时间:晚班:18:00 - 24:00

立即付费处理
快速回复 返回顶部 返回列表