python3使用importlib来重复加载模块

#-*- coding:utf-8 -*-
from socketserver import ThreadingTCPServer, BaseRequestHandler
import importlib
import traceback
import time
import logging
logging.basicConfig(level=logging.DEBUG,
  filename="log/xxgl_%s.log" % (time.strftime("%Y%m%d", time.localtime())),
  filemode='a',
  format='%(asctime)s-%(filename)s[line:%(lineno)d]-%(levelname)s: %(message)s')
module_list = {}

class MyBaseRequestHandler(BaseRequestHandler):
def handle(self):
  #循环监听(读取)来自客户端的数据
  while True:
    try:
      #一次读取1024字节,并去除两端的空白字符(包括空格,TAB,\r,\n)
      data = self.request.recv(1024).strip()
      data = data.decode()
      if data == '':
        break

      #self.client_address是客户端的连接(host, port)的元组
      logging.info("receive from %r: [%r]" % (self.client_address, data))
      ret = self.exec_sub(data, data)
      self.request.sendall(ret.encode())
    except:
      #traceback.print_exc() #当客户端主动断开连接时,self.recv(1024)会抛出异常
      break

def findModule(self, procName):
  try:
    return module_list[procName]
  except:
    logging.debug("module_list[%s] not found" % (procName))
    return None

#根据报文名称调用对应的模块,并传递参数,将执行结果返回给客户端
def exec_sub(self, procName, params):
  try:
    proc = self.findModule(procName)
    logging.debug(str(proc))
    if proc == None:
      proc = importlib.import_module(procName)
      module_list[procName] = proc
      logging.debug('import_module: ' + procName)
    else:
      importlib.reload(proc)
      time.sleep(1) #不延时会重新加载失败
      logging.debug('reload: ' + procName)
    result = proc.call_sub(params)
    return result
  except Exception as e:
    logging.error(str(e))
    return "error"

if __name__ == "__main__":
  host = "" #主机名,可以是ip,像localhost的主机名,或""
  port = 9999 #端口
  addr = (host, port)
  server = ThreadingTCPServer(addr, MyBaseRequestHandler)
  server.serve_forever()

 

posted @ 2019-08-25 10:26  舟山渔夫  阅读(1098)  评论(0编辑  收藏  举报