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
Removing modules from sys.modules requires 'None' types to be deleted as well.
Method 1:
import sys
import json ## your module
for mod in [ m for m in sys.modules if m.lstrip('_').startswith('json') or sys.modules[m] == None ]: del sys.modules[mod]
print( json.dumps( [1] ) ) ## test if functionality has been removed
Method 2, using bookkeeping entries, to remove all dependencies:
import sys
before_import = [mod for mod in sys.modules]
import json ## your module
after_import = [mod for mod in sys.modules if mod not in before_import]
for mod in [m for m in sys.modules if m in after_import or sys.modules[m] == None]: del sys.modules[mod]
print( json.dumps( [2] ) ) ## test if functionality has been removed
Optional, just to be certain all entries are out, if you so choose:
import gc
gc.collect()