使用pythonasyncio时如何重载模块?

2024-04-25 02:10:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pyinotify来跟踪文件更改,并尝试重载修改文件的模块。 但不幸的是,不是模块可能没有超载,我看不到变化。在

import sys
import asyncio
import pyinotify
import importlib
from aiohttp import web
from aa.aa import m_aa


class EventHandler(pyinotify.ProcessEvent):

   def my_init(self, loop=None):
       self.loop = loop if loop else asyncio.get_event_loop()

    def process_IN_MODIFY(self, event):
       pathname = event.pathname
       name = event.name
       if name.endswith('.py'):
            for module in sys.modules.values():
               if hasattr(module, '__file__'):
                   if module.__file__ == pathname:
                       importlib.reload(module)

def inotify_start(loop):
   wm = pyinotify.WatchManager()
   wm.add_watch('/home/test', pyinotify.ALL_EVENTS, rec=True)
   handler = EventHandler( loop=loop )
   pyinotify.AsyncioNotifier(wm, loop, default_proc_fun=handler)


async def init(loop):
   app = web.Application()
   app.router.add_route('GET', '/', m_aa)
   handler = app.make_handler()
   inotify_start(loop)
   srv = await loop.create_server(handler, '0.0.0.0', 8080)
   return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
try:
   loop.run_forever()
except keyboardInterrupt:
   pass

以及来自模块aa.aa的代码文件

^{pr2}$

也许还有别的办法,我需要修改的代码不用手动重新加载。在


Tags: 模块文件importselfloopeventasyncioif