使用 Python 进行热重载/交换

发布于 2024-09-26 03:18:50 字数 283 浏览 2 评论 0原文

我希望代码更改在开发过程中立即生效。如何检测已更改的文件并在正在运行的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幼儿园老大 2024-10-03 03:18:50

我希望我的一些 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

旧城烟雨 2024-10-03 03:18:50

已提出此问题 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.

扭转时空 2024-10-03 03:18:50

这对于大多数应用程序来说没有意义,因为使用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 the django.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文