Skip to main content

Python Sandboxed Evaluator

A Python library for securely evaluating user-provided Python code within a sandboxed environment. This library restricts the execution of code by imposing limits on:

  • Execution Time
  • Memory Usage
  • Allowed Modules (via RestrictedPython)

Features

  • Time Limit: Prevents long-running code from consuming system resources.
  • Memory Limit: Restricts memory usage to avoid overuse of system resources.
  • RestrictedPython Execution: Uses RestrictedPython to prevent access to unsafe Python features.
  • Input Validation: Ensures only safe data types (integers, floats, strings, lists, and dictionaries) are provided as inputs.
  • Logging: Records detailed logs of the evaluation process (success, failure, errors).
  • Test Suite: Pre-built tests for normal execution, timeout, memory overflow, syntax errors, and input validation.

Installation

To install the package from PyPI:

pip install python-sandboxed-evaluator

Usage

Example Usage

Here’s an example of how to use the library to evaluate code with time and memory limits:

from sandbox_evaluator_lib.sandbox_evaluator import SandboxEvaluator

evaluator = SandboxEvaluator(time_limit=1, memory_limit=10 * 1024 * 1024)

# User-provided code (summing two numbers)
user_code = """
result = x + y
"""

# Inputs for the code
inputs = {"x": 5, "y": 7}

# Evaluating the code
result = evaluator.evaluate(user_code, inputs)

print(result)  # Expected output: "Execution completed successfully"

Problem Class Example

You can also use the Problem class to define and validate code problems. Here’s an example:

from sandbox_evaluator_lib.problem import Problem
from sandbox_evaluator_lib.sandbox_evaluator import SandboxEvaluator

if __name__ == '__main__':
  # Creating a Problem with test cases
  test_cases = [
      {"input": {"x": 5, "y": 7}, "expected_output": True},
      {"input": {"x": 2, "y": 3}, "expected_output": False},
  ]

  user_code = """
result = x + y
if result > 10:
  result = True
else:
  result = False
  """

  problem = Problem("Sum two numbers", user_code, test_cases)

  # Validate the problem
  validation_results = problem.validate()

  # Check results
  for case in validation_results:
      if case["passed"]:
          print(f"Test passed for input {case['input']}")
      else:
          print(f"Test failed for input {case['input']} with error: {case['error']}")

Testing

You can run the test suite to ensure everything works correctly:

python -m unittest discover sandbox_evaluator_lib/tests

Time and Memory Limits

The SandboxEvaluator class allows you to set time and memory limits. The following example shows how to set those limits:

evaluator = SandboxEvaluator(time_limit=2, memory_limit=5 * 1024 * 1024)  # 2 seconds, 5 MB
  • time_limit : The maximum time (in seconds) that the code is allowed to run.

  • memory_limit : The maximum memory (in bytes) that the code is allowed to use.

Supported Operations

This library is designed to execute basic Python code, including:

  • Mathematical operations

  • String operations

  • List and dictionary manipulation It does not allow certain operations like:

  • File I/O

  • Network access

  • Modifying system-level settings

Error Handling

When code execution exceeds time or memory limits, or when there’s a syntax error, the evaluator will provide an appropriate error message.

For example:

  • Time Limit Exceeded : "Time limit exceeded (3.5s)"

  • Memory Limit Exceeded : "Memory limit exceeded"

  • Syntax Error : "Error: invalid syntax"

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgements

  • The RestrictedPython library is used for creating the sandboxed environment.

  • The memory_profiler package is used for monitoring memory usage during code execution.

Contributing

Feel free to open issues or submit pull requests for improvements, bug fixes, or new features. Contributions are welcome!

Metadata

Release files for python-sandboxed-evaluator 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-sandboxed-evaluator 0.1.0
File Size Uploaded Provenance Actions
python_sandboxed_evaluator-0.1.0.tar.gz 9.1 kB Without provenance Details for python_sandboxed_evaluator-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for python-sandboxed-evaluator 0.1.0
File Interpreter ABI Platform Actions
python_sandboxed_evaluator-0.1.0-py3-none-any.whl Python 3 none any Details for python_sandboxed_evaluator-0.1.0-py3-none-any.whl

Total release size: 15.7 kB

Release files / python_sandboxed_evaluator-0.1.0.tar.gz

Download URL python_sandboxed_evaluator-0.1.0.tar.gz
Size 9.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2e1a6f496bbd5a07079d1f2cb93bb487c9184c01b86d15fefb6bccf0b1237b87
BLAKE2b-256 checksum
How to use checksums
57a1e859de2c2b17091136e24421f8b87ea9585aa1e3eef2d4a98e2e5678f33c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.9.4

Release files / python_sandboxed_evaluator-0.1.0-py3-none-any.whl

Download URL python_sandboxed_evaluator-0.1.0-py3-none-any.whl
Size 6.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1e772b3c256440f89d263ccab9577b8e820a8763b921045a1019a8d7829d1fb1
BLAKE2b-256 checksum
How to use checksums
81f3a39caac27913fa48a6d69fd229310601acfd0b0cfcfb72f8ff604a6ce258
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.9.4

Security for python-sandboxed-evaluator 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page