如果您已经访问了模块,则通常可以从
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'>
如果你会注意到存在
types的在
subprocess模块只是一个假象
import types在里面的语句。只要
importtypes您需要该模块即可。
实际上,将来的版本
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只是它导入的其他顶级模块。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)