How do I unload (reload) a Python module?

后端 未结 20 2439
轮回少年
轮回少年 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:53

    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.

提交回复
热议问题