我正在对各种模块进行一些解析和内省,但我不想解析内置模块。现在,对于内置模块没有特殊的类型,比如有一个types.BuiltinFunctionType
,那么我该怎么做呢?在
>>> import CornedBeef
>>> CornedBeef
<module 'CornedBeef' from '/meatish/CornedBeef.pyc'>
>>> CornedBeef.__file__
'/meatish/CornedBeef.pyc'
>>> del CornedBeef.__file__
>>> CornedBeef
<module 'CornedBeef' (built-in)>
根据Python,如果模块没有__file__
属性,那么它显然是内置的。这是否意味着hasattr(SomeModule, '__file__')
是检查模块是否内置的方法?当然,这对del SomeModule.__file__
来说并不常见,但是有没有更可靠的方法来确定模块是否是内置的呢?在
您可以使用
imp.is_builtin
来查看模块名是否与内置模块匹配,但我想不出任何方法来真正可靠地反省模块对象。在您也可以尝试以下操作:
^{}
如果你认为它只是被问到,
builtins
,那么接受的答案显然是正确的。在在我的例子中,我也在寻找标准库,我指的是给定Python发行版附带的所有可导入模块的列表。关于这方面的问题已经被问了好几次,但我找不到一个包括我所寻找的一切的答案。在
我的用例是在Python
import x
语句中插入任意一个x
,如下所示:这将适用于virtualenvs或全局安装。它查询运行脚本的任何python二进制文件的分布。最后一块确实超出了virtualenv,但我认为这是期望的行为。在
返回
已排序的导入列表:
[..., 'imaplib', 'imghdr', 'imp', 'importlib', 'imputil', 'inspect', 'io', ...]
说明:
我把它分成几块,这样每个小组需要的原因就可以很清楚了。在
modules
sys.path
上所有加载的模块,并返回(module_loader, name, ispkg)
元组的生成器。在site_packages
modules
列表中删除它们。这大致相当于第三方DEP。在pip
返回的模块名称与PyPi上的一样,而不是导入到源文件中时的名称。某些病理包裹会从裂缝中滑出,比如:requests-futures
作为requests_futures
导入。在colors
,这实际上是PyPi上的{top_level.txt
。我的所有案例都被正确配置了。在system_modules
sys
、gc
、errno
和其他一些{a3}。在top_level_libs
email
、logging
、xml
等。在结论
对于我的2013 MacBookPro,我找到了403个模块用于
^{pr2}$python2.7
安装。在我提出了the code and output的要点。如果你认为我错过了一个类或包含了一个伪造的模块,我想听听。在
*备选方案
在写这篇文章时,我对}API进行了深入的研究。这些信息可能通过单个模块传递,但您确实需要了解如何绕过该API。
pip
和{在我开始之前,有人告诉我,
six
有一个专门针对这个问题的函数。它可能存在,但我自己找不到。相关问题 更多 >
编程相关推荐