Skip to main content
Donate to the Python Software Foundation or Purchase a PyCharm License to Benefit the PSF! Donate Now

Python sandbox

Project description

pysandbox is a Python sandbox. By default, untrusted code executed in the sandbox cannot modify the environment (write a file, use print or import a module). But you can configure the sandbox to choose exactly which features are allowed or not, eg. import sys module and read /etc/issue file.



Blocked Python functions (by default):

  • Deny access to the file system
  • Deny importing Python modules
  • Deny exiting Python
  • Deny access to stdin, stdout or stderr
  • Deny some builtins symbols like execfile(), reload() or KeyboardInterrupt
  • Deny execution of arbitrary bytecode (creation of arbitrary code object)

You can enable all of these features by setting the sandbox configuration.

The default recursion limit is 50 frames.

Protection of the namespace:

  • Deny access to function closure, globals, defaults and code
  • Deny access to frame locals, globals and previous frame
  • Deny access to traceback frame
  • Deny access to types subclasses
  • __builtins__ is read only
  • Deny access to dict methods able to modify a dict, eg. dict.__setitem__. But you can use “d[key] = value” and “del d[key]” instead


pysandbox is unable to limit the memory or the CPU of the sandbox process: you have to use your own protection. Use for example a subprocess to run the untrusted code and use the OS to limit resources (memory and CPU) of the subprocess. Using a subprocess protects also the main process against crash in the untrusted code.

pysandbox is a sandbox for the Python namespace, not a sandbox between Python and the operating system. It does not protect your system against Python security vulnerabilities: vulnerabilities in modules/functions available in your sandbox (depend on your sandbox configuration). By default, only few functions are exposed to the sandbox namespace which limits the attack surface.

See Lib/test/crashers/ directory in the CPython source code to see examples of known bugs crashing the CPython interpreter.


Use SandboxConfig class to configure your sandbox. Features are the most simple way to configure it.


To enable a feature, use SandboxConfig(‘feature1’, ‘feature2’, …) or config.enable(‘feature’). Available features:

  • “codecs”: codecs module
  • “datetime”: datetime module
  • “encodings”: encodings module with ascii, latin_1, utf_8, utf_16_be, utf_32_be and rot_13 codecs (submodules). Enable codecs feature.
  • “exit”: sys.exit(), BaseException, KeyboardInterrupt, SystemExit, quit()
  • “future”: from __future__ import …
  • “hashlib”: hashlib module.
  • “help”:, use “import pydoc” outside the sandbox to use it. Enable regex feature.
  • “interpreter”: give access to standard streams, enable traceback. Enable encodings, exit, site, stdin, stdout, stderr and traceback features.
  • “itertools”: itertools module
  • “math”: math module
  • “random”: random module. Enable hashlib and math features.
  • “regex”: compile regex, match regex, search regex, etc. (re module)
  • “site”: allow to read the license file
  • “stdin”: sys.stdin, input() and raw_input()
  • “stdout”, “stderr”: sys.stdout and sys.stderr
  • “time”: time module (except sleep, strptime and tzset functions)
  • “unicodedata”: unicodedata module, required for u’N{ATOM SYMBOL}’ syntax

The following features are unsafe: only use them if you really understand their impact in term of security. Available unsafe features:

  • “debug_sandbox”: allow to display a traceback of the sandbox. Enable traceback feature.
  • “traceback”: allow access to the frame.f_code attribute. Next calls to allowModule() will add the module filename to the open() whitelist, so Python can display a traceback with the source code. This feature have to be enabled before all other features.

CPython restricted mode

WARNING: CPython restricted mode is unsafe because it is possible to execute arbitrary bytecode.

Use SandboxConfig(cpython_restricted=True) to enable CPython restricted mode. In this mode, reading a file and modify a class are blocked. Some attributes are hidden (eg. method.__self__), other are read only (eg. func.__doc__).

CPython restricted mode is disabled by default. The restricted mode is incompatible with SandboxConfig “traceback” feature and allowPath() method.

The restricted mode doesn’t exist in Python3 anymore, it was removed with bastion and rexec modules:

Other options

  • config.allowPath(path) allows to read a file from the specified path
  • config.allowModule(name, symbol1, symbol2, …) allows to import the specified module, but give only access to the specified symbols


With call() method:

from sandbox import Sandbox

def func(a, b):
    return a + b

sandbox = Sandbox()
print, 1, 2)

With execute() method:

from sandbox import Sandbox, SandboxConfig
sandbox = Sandbox(SandboxConfig('stdout'))
sandbox.execute('print("Code executed in the sandbox")')

execute() with a local variable:

from sandbox import Sandbox, SandboxConfig
sandbox = Sandbox(SandboxConfig('stdout'))
sandbox.execute('print(data)', locals={'data': [1, 2, 3]})    # ok
sandbox.execute('data.append(4)', locals={'data': [1, 2, 3]}) # error

Objects passed to .call() globals/locals and .execute() arguments are proxified: they are replaced by read-only views of the objects.


pysanbox is tested on Python 2.5 and 2.6 on Debian Sid.

See TODO file for the complete status.

See also

Python-dev mailing list


Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
pysandbox-1.5.1.tar.gz (30.7 kB) Copy SHA256 hash SHA256 Source None

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page