I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What\'s the best way do do this?
if foo.py
The accepted answer doesn't handle the from X import Y case. This code handles it and the standard import case as well:
def importOrReload(module_name, *names):
import sys
if module_name in sys.modules:
reload(sys.modules[module_name])
else:
__import__(module_name, fromlist=names)
for name in names:
globals()[name] = getattr(sys.modules[module_name], name)
# use instead of: from dfly_parser import parseMessages
importOrReload("dfly_parser", "parseMessages")
In the reloading case, we reassign the top level names to the values stored in the newly reloaded module, which updates them.