How do I unload (reload) a Python module?

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

    This is the modern way of reloading a module:

    from importlib import reload
    

    If you want to support versions of Python older than 3.5, try this:

    from sys import version_info
    if version_info[0] < 3:
        pass # Python 2 has built in reload
    elif version_info[0] == 3 and version_info[1] <= 4:
        from imp import reload # Python 3.0 - 3.4 
    else:
        from importlib import reload # Python 3.5+
    

    To use it, run reload(MODULE), replacing MODULE with the module you want to reload.

    For example, reload(math) will reload the math module.

提交回复
热议问题