禁止在Python中使用import语句导入

2024-09-28 22:57:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想限制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.

但事实并非如此。我将非常感谢你解释为什么以及如何实现我的目标的建议


Tags: 模块the方法importselfdefnotargs
2条回答

您有一个误解:文档并不建议在模块中定义您自己的__import__函数。他们想说的是当你有一个像

import mymodule

那么这里解析名称mymodule的方法是通过以下方式调用the built-in function ^{}

^{pr2}$

如果要阻止模块成功导入,只需将语法错误或运行时错误代码放在其中,例如,将以下内容作为文件的第一行:

# my_unimportable_file.py
errorerrorerror

语句import module_name使用参数'module_name'调用内置函数__import__。它没有,事实上也不能像您预期的那样调用module_name.__import__(),因为模块本身还没有加载。在

一个很好的方法是检查不可导入模块中的__name__全局变量。当它运行时,它应该等于'__main__',但是当它被导入时,它将是根据它的名称构造的其他字符串。因此,您可以尝试:

if __name__ != '__main__':
    raise ImportError("Imports are not allowed")

相关问题 更多 >