.. image:: https://github.com/zopefoundation/RestrictedPython/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/RestrictedPython/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/RestrictedPython/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/RestrictedPython?branch=master
.. image:: https://readthedocs.org/projects/restrictedpython/badge/ :target: https://restrictedpython.readthedocs.org/ :alt: 文档状态
.. image:: https://img.shields.io/pypi/v/RestrictedPython.svg :target: https://pypi.org/project/RestrictedPython/ :alt: PyPI 上的当前版本
.. image:: https://img.shields.io/pypi/pyversions/RestrictedPython.svg :target: https://pypi.org/project/RestrictedPython/ :alt: 支持的 Python 版本
.. image:: https://github.com/zopefoundation/RestrictedPython/raw/master/docs/logo.jpg
================ RestrictedPython
RestrictedPython 是一种工具,用于定义 Python 语言的子集,从而能够将程序输入放入受信任的环境中。 RestrictedPython 并非沙箱系统或安全环境,但它有助于定义受信任的环境,并在其中执行不可信的代码。
.. warning::
RestrictedPython 仅支持 CPython。它不支持 PyPy 及其他 Python 实现,因为它无法为这些实现施加相应的限制。
如需完整文档,请访问 http://restrictedpython.readthedocs.io/。
示例
为让大家对 RestrictedPython 的功能有基本了解,这里给出两个示例:
无问题的代码示例
Python 允许执行大量命令,而这些命令不会对任何系统造成损害。
.. code-block:: pycon
>>> from RestrictedPython import compile_restricted
>>> from RestrictedPython import safe_globals
>>>
>>> source_code = """
... def example():
... return 'Hello World!'
... """
>>>
>>> loc = {}
>>> byte_code = compile_restricted(source_code, '<inline>', 'exec')
>>> exec(byte_code, safe_globals, loc)
>>>
>>> loc['example']()
'Hello World!'
有问题的代码示例
如果在 Python 中直接运行此示例,可能会损害您的系统。
.. code-block:: pycon
>>> from RestrictedPython import compile_restricted
>>> from RestrictedPython import safe_globals
>>>
>>> source_code = """
... import os
...
... os.listdir('/')
... """
>>> byte_code = compile_restricted(source_code, '<inline>', 'exec')
>>> exec(byte_code, safe_globals, {})
Traceback (most recent call last):
ImportError: __import__ not found
为 RestrictedPython 做贡献
如果您希望协助维护 RestrictedPython 并做出贡献,请参阅文档中的 Contributing page <https://restrictedpython.readthedocs.io/en/latest/contributing/index.html>_ 部分。