有没有办法在Python中访问父模块

有没有办法在Python中访问父模块,第1张

有没有办法在Python中访问父模块

如果您已经访问了模块,则通常可以从

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
只是它导入的其他顶级模块。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5649618.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存