检测python模块是否更改然后重新加载 [英] Detect if a python module changes and then reload

查看:704
本文介绍了检测python模块是否更改然后重新加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在开发一个包含许多模块的相当大的python项目。 main(可运行)模块是一个守护进程(实际上是一个Thrift守护进程),它为其实际功能调用其他模块。启动守护进程需要很长时间,因为某些模块具有相当冗长且涉及的初始化过程。

So I'm developing a rather large python project with a number of modules. The "main" (runnable) module is a daemon (a Thrift daemon, actually) which calls off to other modules for its actual functionality. Starting up the daemon takes a long time because some of the modules have a rather lengthy and involved initialization processes.

因此,当我启动守护进程时,我等待...让我们说...加载所有东西需要2分钟,这在宏伟的计划中并不算太糟糕。然而,对于开发而言,它变成了一个主要的痛苦,因为我需要每次都重新启动守护进程,这一直浪费了我很多时间。

So when I start the daemon, I wait... let's say... 2 minutes for everything to load, which isn't too bad in the grand scheme of things. However for development it becomes a major pain because I need to restart the daemon EVERY TIME which has been wasting a lot of my time.

大多数模块只需要几秒钟加载。理想情况下,我想要做的是检测特定模块中的任何文件何时发生更改,然后重新加载该特定模块。我已经找到了如何重新加载模块,但此时我无法弄清楚如何观察特定模块的更改。请记住,在这种情况下,模块不是单个 .py 文件,而是具有 __ init __。py 和5-10 .py 文件,因此我需要检测任何的更改时间。

Most modules only takes a few seconds to load. Ideally what I'd like to do is detect when any of the files in a particular module have changed, and reload that particular module. I've already figured out how to reload a module, but at this point I can't figure out how to watch a particular module for changes. Keep in mind that a module isn't a single .py file in this case, but rather a directory with __init__.py and 5-10 .py files, so I need to detect when any of them have changed.

这是项目布局(如果它有任何区别)

Here is the project layout (if it makes any difference at all)

project
| -- daemonize.py
| -- main.py
| -- moduleA
|    | -- __init__.py
|    | -- happy_panda.py
|    ` -- sad_panda.py
| -- moduleB
|    | -- __init__.py
|    | -- takes_forever_to_load.py
|    ` -- seriously_get_some_coffee.py
| -- moduleC
|    | -- __init__.py
|    | -- frequently_changes.py
|    | -- reasons_i_hate_my_job.txt
|    ` -- home_address_of_moduleB_developer.txt
` -- service.py <-- uses modules A, B, and C

任何想法或建议都表示赞赏。

Any ideas or suggestions are appreciated.

编辑

感谢您的反馈。这是我根据建议创建的代码。有一个小错误,其中pyinotify似乎获得了多个通知,但这对我来说是一个非常小的问题,所以我不打算修复它。

Thanks for the great feedback. Here is the code I created based on the suggestions. There's a small bug where pyinotify seems to be getting more than one notification, but it's a very small problem for me so I'm not going to fix it.

https://gist.github.com/1013122

推荐答案

在没有轮询的情况下检测文件更改

再加上你已经知道如何重新加载你的模块这个答案几乎填补了它。当文件被修改时,它使用Inotify通知(看看他们在那里做了什么)程序。

Coupled with you already knowing how to reload your module this answer pretty much fills it out. It uses Inotify to "notify" (see what they did there) the program when the file is modified.

这篇关于检测python模块是否更改然后重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆