CPython中的子解释器API的目的是什么?
我不清楚子解释器API为何存在以及为什么在诸如mod_wsgi apache模块之类的模块中使用它.它是主要用于为在同一进程中运行的不同应用程序创建安全沙箱,还是一种允许多线程并发的方法?也许两者都有?还有其他目的吗?
I'm unclear on why the sub-interpreter API exists and why it's used in modules such as the mod_wsgi apache module. Is it mainly used for creating a security sandbox for different applications running within the same process, or is it a way to allow concurrency with multiple threads? Maybe both? Are there other purposes?
我想象的目的是创建单独的python执行环境.例如, mod_wsgi (Apache Python模块)承载一个python解释器,然后在其中托管多个应用程序子解释器(默认配置).
I imagine the purpose is to create separate python execution environments. For instance, mod_wsgi (Apache Python module) hosts a single python interpreter and then hosts multiple applications within sub-interpreters (in the default configuration).
文档中的一些关键点:
- 这是一个(几乎)完全独立的环境,用于执行Python代码.特别是,新的解释器对所有导入的模块具有单独的独立版本,包括基本模块
__builtin__
,__main__
和sys
. - 加载的模块(sys.modules)表和模块搜索路径(sys.path)也分开.
- 由于子解释器(和主解释器)是同一过程的一部分,因此它们之间的隔离并不是完美的-例如,使用低级文件操作(例如os.close()),它们可以(偶然或恶意地) )会影响彼此的打开文件.
- 由于(子)解释程序之间共享扩展的方式,某些扩展可能无法正常工作;当扩展程序使用(静态)全局变量,或者扩展程序在初始化后对其模块的字典进行操作时,这种情况尤其可能发生.
- This is an (almost) totally separate environment for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules, including the fundamental modules
__builtin__
,__main__
andsys
. - The table of loaded modules (sys.modules) and the module search path (sys.path) are also separate.
- Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn’t perfect — for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect each other’s open files.
- Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when the extension makes use of (static) global variables, or when the extension manipulates its module’s dictionary after its initialization.