Skip to main content
 首页 » 编程设计

python之如何在导入过程中忽略 python 模块

2024年10月01日7小虾米

在 Python 应用程序的构建过程中,我需要忽略一些导入(因为这些模块是由构建过程创建的)。这是一个先有鸡还是先有蛋的问题,我无法轻易解决。 所以我想我可以使用导入 Hook 来这样做:

class ImportBlocker(object): 
    def __init__(self, *args): 
        self.module_names = args 
 
    def find_module(self, fullname, path=None): 
        if fullname in self.module_names: 
            return self 
        return None 
 
    def load_module(self, name): 
        raise ImportError("%s is blocked and cannot be imported" % name) 
 
import sys 
sys.meta_path = [ImportBlocker('chickenlib')] 

但是因为我提出了一个错误,构建过程停止了——我只想静静地忽略导入……返回“无”也不起作用。 有办法做到这一点吗?

请您参考如下方法:

如果您使用的是 Python 3.4 或更高版本,您可以通过稍微修改您的示例来实现将创建一个空模块。

class ImportBlocker(object): 
    def __init__(self, *args): 
        self.module_names = args 
 
    def find_module(self, fullname, path=None): 
        if fullname in self.module_names: 
            return self 
        return None 
 
    def exec_module(self, mdl): 
        # return an empty namespace 
        return {} 

现在:

>>> import sys 
>>> sys.meta_path = [ImportBlocker('chickenlib')] 
 
>>> # this will work fine 
>>> import chickenlib 
 
>>> # there is nothing useful in your imported module 
>>> print(vars(chickenlib)) 
{'__doc__': None, '__package__': '', '__name__': 'chickenlib', '__loader__': <__main__.ImportBlocker object at 0x102b8c470>, '__spec__': ModuleSpec(name='chickenlib', loader=<__main__.ImportBlocker object at 0x102b8c470>)}