How do I unload (reload) a Python module?

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

    If you are not in a server, but developing and need to frequently reload a module, here's a nice tip.

    First, make sure you are using the excellent IPython shell, from the Jupyter Notebook project. After installing Jupyter, you can start it with ipython, or jupyter console, or even better, jupyter qtconsole, which will give you a nice colorized console with code completion in any OS.

    Now in your shell, type:

    %load_ext autoreload
    %autoreload 2
    

    Now, every time you run your script, your modules will be reloaded.

    Beyond the 2, there are other options of the autoreload magic:

    %autoreload
    Reload all modules (except those excluded by %aimport) automatically now.
    
    %autoreload 0
    Disable automatic reloading.
    
    %autoreload 1
    Reload all modules imported with %aimport every time before executing the Python code typed.
    
    %autoreload 2
    Reload all modules (except those excluded by %aimport) every time before
    executing the Python code typed.
    

提交回复
热议问题