How do I unload (reload) a Python module?

后端 未结 20 2351
轮回少年
轮回少年 2020-11-21 05:20

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          


        
20条回答
  •  情深已故
    2020-11-21 05:35

    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()
    

提交回复
热议问题