How do I unload (reload) a Python module?

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

    For Python 2 use built-in function reload():

    reload(module)
    

    For Python 2 and 3.2–3.3 use reload from module imp:

    import imp
    imp.reload(module)
    

    But imp is deprecated since version 3.4 in favor of importlib, so use:

    import importlib
    importlib.reload(module)
    

    or

    from importlib import reload
    reload(module)
    

提交回复
热议问题