How do I unload (reload) a Python module?

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

    It can be especially difficult to delete a module if it is not pure Python.

    Here is some information from: How do I really delete an imported module?

    You can use sys.getrefcount() to find out the actual number of references.

    >>> import sys, empty, os
    >>> sys.getrefcount(sys)
    9
    >>> sys.getrefcount(os)
    6
    >>> sys.getrefcount(empty)
    3
    

    Numbers greater than 3 indicate that it will be hard to get rid of the module. The homegrown "empty" (containing nothing) module should be garbage collected after

    >>> del sys.modules["empty"]
    >>> del empty
    

    as the third reference is an artifact of the getrefcount() function.

提交回复
热议问题