这是一个如何使用 pyinotify 实现的示例(即在 Linux 上)。
from importlib import import_module
class RestartingLauncher:
def __init__(self, module_name, start_function, stop_function, path="."):
self._module_name = module_name
self._filename = '%s.py' % module_name
self._start_function = start_function
self._stop_function = stop_function
self._path = path
self._setup()
def _setup(self):
import pyinotify
self._wm = pyinotify.WatchManager()
self._notifier = pyinotify.ThreadedNotifier(
self._wm, self._on_file_modified)
self._notifier.start()
# We monitor the directory (instead of just the file) because
# otherwise inotify gets confused by editors such a Vim.
flags = pyinotify.EventsCodes.OP_FLAGS['IN_MODIFY']
wdd = self._wm.add_watch(self._path, flags)
def _on_file_modified(self, event):
if event.name == self._filename:
print "File modification detected. Restarting application..."
self._reload_request = True
getattr(self._module, self._stop_function)()
def run(self):
self._module = import_module(self._module_name)
self._reload_request = True
while self._reload_request:
self._reload_request = False
reload(self._module)
getattr(self._module, self._start_function)()
print 'Bye!'
self._notifier.stop()
def launch_app(module_name, start_func, stop_func):
try:
import pyinotify
except ImportError:
print 'Pyinotify not found. Launching app anyway...'
m = import_module(self._module_name)
getattr(m, start_func)()
else:
RestartingLauncher(module_name, start_func, stop_func).run()
if __name__ == '__main__':
launch_app('example', 'main', 'force_exit')
launch_app 调用中的参数是文件名(不带“.py”)、开始执行的函数和以某种方式停止执行的函数。
这是一个可以使用之前的代码(重新)启动的“应用程序”的愚蠢示例:
run = True
def main():
print 'in...'
while run: pass
print 'out'
def force_exit():
global run
run = False
在您想要使用它的典型应用程序中,您可能会有某种主循环。下面是一个更真实的示例,用于基于 GLib/GTK+ 的应用程序:
from gi.repository import GLib
GLib.threads_init()
loop = GLib.MainLoop()
def main():
print "running..."
loop.run()
def force_exit():
print "stopping..."
loop.quit()
同样的概念适用于大多数其他循环(Clutter、Qt 等)。
监控多个代码文件(即应用程序的所有文件)和错误恢复能力(例如,打印异常并在空闲循环中等待代码修复,然后再次启动)作为练习留给读者:)。
注意:此答案中的所有代码均在 ISC 许可下发布(除了知识共享)。