How can I block a Python stdlib module from being imported?

折月煮酒 提交于 2019-12-06 11:04:33

问题


In my Python script, I want to prevent certain stdlib modules, such as os and sys, from being imported. How would I accomplish this?


回答1:


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:

import sys
sys.modules['os'] = None
sys.modules['system'] = None

Of course, there is no module system so you might have meant sys, 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.




回答2:


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.



来源:https://stackoverflow.com/questions/7842852/how-can-i-block-a-python-stdlib-module-from-being-imported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!