我怀疑我想要清理.
考虑以下名为的模块ex_1.py:
print("Hello, I'm ex_1")
def greet(name):
print("Hello, "+name+" nice to meet you! ")
Run Code Online (Sandbox Code Playgroud)
现在考虑调用另一个1_client_ex_1.py将导入ex_1.py模块的文件.
import ex_1.py
Run Code Online (Sandbox Code Playgroud)
现在,当我执行此文件时,我得到的输出为:
Hello, I'm ex_1
Run Code Online (Sandbox Code Playgroud)
正如所料.
但是当我1_client_ex_1.py改为:
import ex_1.py
import ex_1.py
Run Code Online (Sandbox Code Playgroud)
并执行它,它仍然只打印Hello, I'm ex_1一次.不应该打印两次吗?
Tho*_*zco 47
没有,如果已导入模块,则不会再次加载.
您只需获得已导入模块的引用(它将来自sys.modules).
要获取已导入的模块列表,您可以查找sys.modules.keys()(请注意,urllib此处导入了许多其他模块):
>>> import sys
>>> print len(sys.modules.keys())
44
>>> print sys.modules.keys()
['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', 'virtualenvwrapper', '_osx_support', 'codecs', 'readline', 'os.path', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']
>>> import urllib
>>> print len(sys.modules.keys())
70
>>> print sys.modules.keys()
['cStringIO', 'heapq', 'base64', 'copy_reg', 'sre_compile', '_collections', '_sre', 'functools', 'encodings', 'site', '__builtin__', 'sysconfig', 'thread', '_ssl', '__main__', 'operator', 'encodings.encodings', '_heapq', 'abc', 'posixpath', '_weakrefset', 'errno', '_socket', 'binascii', 'encodings.codecs', 'urllib', 'sre_constants', 're', '_abcoll', 'collections', 'types', '_codecs', 'encodings.__builtin__', '_struct', '_warnings', '_scproxy', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'string', 'warnings', 'UserDict', 'struct', 'encodings.utf_8', 'textwrap', 'sys', 'ssl', 'virtualenvwrapper', '_osx_support', 'codecs', 'readline', 'os.path', 'strop', '_functools', 'sitecustomize', 'socket', 'keyword', 'signal', 'traceback', 'urlparse', 'linecache', 'itertools', 'posix', 'encodings.aliases', 'time', 'exceptions', 'sre_parse', 'os', '_weakref']
>>> import urllib #again!
>>> print len(sys.modules.keys()) #has not loaded any additional modules
70
Run Code Online (Sandbox Code Playgroud)
让我们给它一个旋转:
import sys
>>> sys.modules["foo"] = "bar" # Let's pretend we imported a module named "foo", which is a string.
>>> print __import__("foo")
bar # Not a module, that's my string!
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,如果找到一个模块sys.modules,您将获得一个新的引用.而已.
请注意,这意味着模块的设计应使其在导入时不会产生副作用(如打印件).
在交互式会话之外重新加载模块通常也不是一个很好的做法(虽然它有它的用例) - 其他答案将详细说明你是如何做到这一点的.
Python脚本只会加载一次模块。要重新加载它,请使用:
reload() # Python 2
Run Code Online (Sandbox Code Playgroud)
和
imp.reload() # Python 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15165 次 |
| 最近记录: |