使用 Python 进行热重载/交换
我希望代码更改在开发过程中立即生效。如何检测已更改的文件并在正在运行的 Python (2.7) 应用程序中重新加载它们?
编辑:
阅读“Ivo van der Wijk”链接的页面后,我认为最好在代码更改时重新启动 Web 应用程序 - 就像 Django 那样。所以实际的问题是:如何监视文件修改?
I want code changes to take effect immediately during development. How can I detect changed files and reload them in the running Python (2.7) application?
Edit:
After reading the pages linked by 'Ivo van der Wijk', I think it would be best to restart the web application when code changes - like Django does. So the actual question is: How to monitor file modifications?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我希望我的一些 Python 脚本也能达到同样的效果,所以我继续制作了脚本 SourceChangeMonitor.py。您可以按照说明此处< /a>.如果您只想要脚本,这里是直接关联
I wanted the same effect for some of my Python scripts, so I went on and made the script SourceChangeMonitor.py. You can find it with instructions here. If you just want the script, here is a direct link
已提出此问题 a 数字 times
您可以使用 reload(module) 来实现此目的,但要注意令人讨厌的副作用。例如,现有代码将基于原始代码,它不会神奇地添加新属性或基类。
This question has been asked a number of times
You can use reload(module) for this, but beware of nasty side effects. For example, existing code will be based on the original code, it will not magically get new attributes or baseclasses added.
这对于大多数应用程序来说没有意义,因为使用
reload
会产生副作用。再加上您花在检测更改和重新加载所有模块的代码上的时间本来可以花在重新启动应用程序上。如果您导入大量模块或有一个包含许多子模块的项目,则非常复杂。在某些情况下,这是一个好主意。 Django Web 框架提供了一个开发服务器 (
manage.py runserver
),可以自动重新加载更改的模块。看一下 django.utils.autoreload - 它使用文件的修改时间来测试所有 Python 文件的修改情况。如前所述,这仅对于某些应用程序来说是一个好主意。 Web 应用程序在某种程度上是无状态的,因此可以重新加载,几乎没有副作用。This does not make sense for most applications because you will get side effects by using
reload
. Plus the time you spend on the code that detects changes and reloads all modules could have been spent on just restarting the application. It's very complicated if you import lots of modules or have a project that contains many sub-modules.In some cases, it's a good idea though. The Django web framework provides a development server (
manage.py runserver
) that automatically reloads changed modules. Take a look at thedjango.utils.autoreload
- it tests all Python files for modifications using the modification time of the files. As said before, this is only a good idea for some applications. Web applications are somewhat stateless and thus can be reloaded with few to no side effects.