如果您已经访问了一个模块,通常可以从sys.modules
字典中获取它。Python不会保留名称的“父指针”,特别是因为关系不是一对一的。例如,使用您的示例:
>>> from subprocess import types
>>> types
<module 'types' from '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc'>
>>> import sys
>>> sys.modules['subprocess']
<module 'subprocess' from '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.pyc'>
如果你注意到
subprocess
模块中存在
types
,那只是因为在其中有
import types
语句。如果你需要该模块,只需
import types
即可。
实际上,未来版本的
subprocess
可能不再导入
types
,这将导致你的代码出现错误。你应该只导入模块中出现在
__all__
列表中的名称;其他名称视为实现细节。
例如:
>>> import subprocess
>>> dir(subprocess)
['CalledProcessError', 'MAXFD', 'PIPE', 'Popen', 'STDOUT', '_PIPE_BUF', '__all__', '__builtins__', '__doc__',
'__file__', '__name__', '__package__', '_active', '_cleanup', '_demo_posix', '_demo_windows', '_eintr_retry_call',
'_has_poll', 'call', 'check_call', 'check_output', 'errno', 'fcntl', 'gc', 'list2cmdline', 'mswindows', 'os',
'pickle', 'select', 'signal', 'sys', 'traceback', 'types']
>>> subprocess.__all__
['Popen', 'PIPE', 'STDOUT', 'call', 'check_call', 'check_output', 'CalledProcessError']
你可以看到,大多数在 subprocess
中可见的名称实际上只是其他它导入的顶级模块。
types
实际上是标准的Pythontypes
模块。你的导入语句与import types
的作用相同,而且在两种情况下types
对象将完全相同。 - Sven Marnachtypes
模块并没有任何有意义或有用的“父级”关系。显然,subprocess
已经导入了types
,就像许多其他模块一样导入了types
。你想要做什么? - John Machin