如何阻止导入 Python stdlib 模块?
在我的 Python 脚本中,我想阻止导入某些 stdlib 模块,例如 os 和 sys 。我将如何实现这个目标?
In my Python script, I want to prevent certain stdlib modules, such as os
and sys
, from being imported. How would I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从字面上理解,如果您的意思只是“将它们存根,以便它们不会通过直接导入加载”,而不是“使它们可以通过不受信任的代码卸载”,那么:
当然,没有模块
system
所以你可能指的是sys
,在这种情况下你就有麻烦了。如果您想阻止不受信任的代码做坏事,请查看 http:// /wiki.python.org/moin/SandboxedPython 并意识到您所追求的东西并不是立即可行的。
Taking you very literally, and if you just mean "to stub them out so that they won't be loaded by a straight import", not "make them unloadable by untrusted code", then:
Of course, there is no module
system
so you might have meantsys
, in which case you're in trouble.If you're trying to keep untrusted code from being able to do Bad Things, then take a look at http://wiki.python.org/moin/SandboxedPython and realise that you're after something not immediately feasible.
不要导入它们。更一般地说,不要在模块内执行不受信任的代码。
eval()
看起来很漂亮,但几乎可以肯定它不是你的朋友。如果您打算对外部代码进行沙箱处理,请参阅 Python wiki 上的 SandboxedPython 文章。在您阅读(并理解)其中的所有内容之前,请不要尝试。
Don't import them. More generally, don't execute untrusted code inside your module.
eval()
looks spiffy but it's almost certainly not your friend.If you're intent on sandboxing external code, look at the SandboxedPython article on the Python wiki. Until you've read (and understood) everything there, please don't try it.