How do I unload (reload) a Python module?

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

    I got a lot of trouble trying to reload something inside Sublime Text, but finally I could wrote this utility to reload modules on Sublime Text based on the code sublime_plugin.py uses to reload modules.

    This below accepts you to reload modules from paths with spaces on their names, then later after reloading you can just import as you usually do.

    def reload_module(full_module_name):
        """
            Assuming the folder `full_module_name` is a folder inside some
            folder on the python sys.path, for example, sys.path as `C:/`, and
            you are inside the folder `C:/Path With Spaces` on the file 
            `C:/Path With Spaces/main.py` and want to re-import some files on
            the folder `C:/Path With Spaces/tests`
    
            @param full_module_name   the relative full path to the module file
                                      you want to reload from a folder on the
                                      python `sys.path`
        """
        import imp
        import sys
        import importlib
    
        if full_module_name in sys.modules:
            module_object = sys.modules[full_module_name]
            module_object = imp.reload( module_object )
    
        else:
            importlib.import_module( full_module_name )
    
    def run_tests():
        print( "\n\n" )
        reload_module( "Path With Spaces.tests.semantic_linefeed_unit_tests" )
        reload_module( "Path With Spaces.tests.semantic_linefeed_manual_tests" )
    
        from .tests import semantic_linefeed_unit_tests
        from .tests import semantic_linefeed_manual_tests
    
        semantic_linefeed_unit_tests.run_unit_tests()
        semantic_linefeed_manual_tests.run_manual_tests()
    
    if __name__ == "__main__":
        run_tests()
    

    If you run for the first time, this should load the module, but if later you can again the method/function run_tests() it will reload the tests files. With Sublime Text (Python 3.3.6) this happens a lot because its interpreter never closes (unless you restart Sublime Text, i.e., the Python3.3 interpreter).

提交回复
热议问题