hot reloading / swapping with Python [duplicate]
Asked Answered
H

3

10

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?

Hambletonian answered 5/10, 2010 at 10:41 Comment(0)
S
5

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.

Salvucci answered 5/10, 2010 at 10:43 Comment(0)
B
9

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

Benghazi answered 10/11, 2011 at 11:19 Comment(1)
Thanks I like it. I ported it to python3 if anyone is interested: github.com/makerGeek/python-hotreloadBalzac
S
5

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.

Salvucci answered 5/10, 2010 at 10:43 Comment(0)
H
1

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.

Hooker answered 5/10, 2010 at 10:51 Comment(1)
Django reloads the entire program when a module changes. Reloading individual modules is extremely dangerous, especially since you're doing it during development when the problems it'll cause will get mixed in with the real bugs you're trying to fix, compounding the problem badly.Claudell

© 2022 - 2024 — McMap. All rights reserved.