我想限制Python3中某些模块的导入(但是对于这个问题的范围,假设我想要限制任何导入)。这就是我尝试的方法:
def __import__(self, *args, **kwrgs):
raise ImportError("Imports are not allowed")
import math
print math.sqrt(4)
我的理解是,这应该引发异常,并且它是基于文档-https://docs.python.org/3/reference/import.html#importsystem的
The search operation of the import statement is defined as a call to the __import__() function, with the appropriate arguments.
但事实并非如此。我将非常感谢你解释为什么以及如何实现我的目标的建议
您有一个误解:文档并不建议在模块中定义您自己的
__import__
函数。他们想说的是当你有一个像那么这里解析名称} :
^{pr2}$mymodule
的方法是通过以下方式调用the built-in function ^{如果要阻止模块成功导入,只需将语法错误或运行时错误代码放在其中,例如,将以下内容作为文件的第一行:
语句
import module_name
使用参数'module_name'
调用内置函数__import__
。它没有,事实上也不能像您预期的那样调用module_name.__import__()
,因为模块本身还没有加载。在一个很好的方法是检查不可导入模块中的
__name__
全局变量。当它运行时,它应该等于'__main__'
,但是当它被导入时,它将是根据它的名称构造的其他字符串。因此,您可以尝试:相关问题 更多 >
编程相关推荐