python-sandboxed-evaluator


Namepython-sandboxed-evaluator JSON
Version 0.1.0 PyPI version JSON
download
home_pagehttps://github.com/iam-mhaseeb/Python-Sandboxed-Evaluator
SummaryA Python library for securely evaluating Python code in a sandboxed environment.
upload_time2025-01-10 05:36:09
maintainerNone
docs_urlNone
authorMuhammad Haseeb
requires_python>=3.6
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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:

```bash
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:


```python
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:

```python
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:


```bash
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:

```python
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](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!


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/iam-mhaseeb/Python-Sandboxed-Evaluator",
    "name": "python-sandboxed-evaluator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": null,
    "author": "Muhammad Haseeb",
    "author_email": "mhaseeb.inbox@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/57/a1/e859de2c2b17091136e24421f8b87ea9585aa1e3eef2d4a98e2e5678f33c/python_sandboxed_evaluator-0.1.0.tar.gz",
    "platform": null,
    "description": "# Python Sandboxed Evaluator\n\nA Python library for securely evaluating user-provided Python code within a sandboxed environment. This library restricts the execution of code by imposing limits on:\n\n- **Execution Time**\n- **Memory Usage**\n- **Allowed Modules (via RestrictedPython)**\n\n## Features\n\n- **Time Limit**: Prevents long-running code from consuming system resources.\n- **Memory Limit**: Restricts memory usage to avoid overuse of system resources.\n- **RestrictedPython Execution**: Uses `RestrictedPython` to prevent access to unsafe Python features.\n- **Input Validation**: Ensures only safe data types (integers, floats, strings, lists, and dictionaries) are provided as inputs.\n- **Logging**: Records detailed logs of the evaluation process (success, failure, errors).\n- **Test Suite**: Pre-built tests for normal execution, timeout, memory overflow, syntax errors, and input validation.\n\n## Installation\n\nTo install the package from PyPI:\n\n```bash\npip install python-sandboxed-evaluator\n```\n\n## Usage \n\n### Example Usage \n\nHere\u2019s an example of how to use the library to evaluate code with time and memory limits:\n\n\n```python\nfrom sandbox_evaluator_lib.sandbox_evaluator import SandboxEvaluator\n\nevaluator = SandboxEvaluator(time_limit=1, memory_limit=10 * 1024 * 1024)\n\n# User-provided code (summing two numbers)\nuser_code = \"\"\"\nresult = x + y\n\"\"\"\n\n# Inputs for the code\ninputs = {\"x\": 5, \"y\": 7}\n\n# Evaluating the code\nresult = evaluator.evaluate(user_code, inputs)\n\nprint(result)  # Expected output: \"Execution completed successfully\"\n```\n\n### Problem Class Example \nYou can also use the `Problem` class to define and validate code problems. Here\u2019s an example:\n\n```python\nfrom sandbox_evaluator_lib.problem import Problem\nfrom sandbox_evaluator_lib.sandbox_evaluator import SandboxEvaluator\n\nif __name__ == '__main__':\n  # Creating a Problem with test cases\n  test_cases = [\n      {\"input\": {\"x\": 5, \"y\": 7}, \"expected_output\": True},\n      {\"input\": {\"x\": 2, \"y\": 3}, \"expected_output\": False},\n  ]\n\n  user_code = \"\"\"\nresult = x + y\nif result > 10:\n  result = True\nelse:\n  result = False\n  \"\"\"\n\n  problem = Problem(\"Sum two numbers\", user_code, test_cases)\n\n  # Validate the problem\n  validation_results = problem.validate()\n\n  # Check results\n  for case in validation_results:\n      if case[\"passed\"]:\n          print(f\"Test passed for input {case['input']}\")\n      else:\n          print(f\"Test failed for input {case['input']} with error: {case['error']}\")\n\n```\n\n### Testing \n\nYou can run the test suite to ensure everything works correctly:\n\n\n```bash\npython -m unittest discover sandbox_evaluator_lib/tests\n```\n\n### Time and Memory Limits \nThe `SandboxEvaluator` class allows you to set time and memory limits. The following example shows how to set those limits:\n\n```python\nevaluator = SandboxEvaluator(time_limit=2, memory_limit=5 * 1024 * 1024)  # 2 seconds, 5 MB\n```\n \n- **time_limit** : The maximum time (in seconds) that the code is allowed to run.\n \n- **memory_limit** : The maximum memory (in bytes) that the code is allowed to use.\n\n### Supported Operations \n\nThis library is designed to execute basic Python code, including:\n\n- Mathematical operations\n\n- String operations\n\n- List and dictionary manipulation\nIt **does not**  allow certain operations like:\n- File I/O\n\n- Network access\n\n- Modifying system-level settings\n\n### Error Handling \n\nWhen code execution exceeds time or memory limits, or when there\u2019s a syntax error, the evaluator will provide an appropriate error message.\n\nFor example:\n \n- **Time Limit Exceeded** : \"Time limit exceeded (3.5s)\"\n \n- **Memory Limit Exceeded** : \"Memory limit exceeded\"\n \n- **Syntax Error** : \"Error: invalid syntax\"\n\n## License \nThis project is licensed under the MIT License - see the [LICENSE](LICENSE)  file for details.\n\n## Acknowledgements \n \n- The **RestrictedPython**  library is used for creating the sandboxed environment.\n \n- The **memory_profiler**  package is used for monitoring memory usage during code execution.\n\n## Contributing \n\nFeel free to open issues or submit pull requests for improvements, bug fixes, or new features. Contributions are welcome!\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A Python library for securely evaluating Python code in a sandboxed environment.",
    "version": "0.1.0",
    "project_urls": {
        "Homepage": "https://github.com/iam-mhaseeb/Python-Sandboxed-Evaluator"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "81f3a39caac27913fa48a6d69fd229310601acfd0b0cfcfb72f8ff604a6ce258",
                "md5": "3223cddcd6b590a58faca31689758f35",
                "sha256": "1e772b3c256440f89d263ccab9577b8e820a8763b921045a1019a8d7829d1fb1"
            },
            "downloads": -1,
            "filename": "python_sandboxed_evaluator-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3223cddcd6b590a58faca31689758f35",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 6680,
            "upload_time": "2025-01-10T05:36:06",
            "upload_time_iso_8601": "2025-01-10T05:36:06.958207Z",
            "url": "https://files.pythonhosted.org/packages/81/f3/a39caac27913fa48a6d69fd229310601acfd0b0cfcfb72f8ff604a6ce258/python_sandboxed_evaluator-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "57a1e859de2c2b17091136e24421f8b87ea9585aa1e3eef2d4a98e2e5678f33c",
                "md5": "7c264f0aa0a66745431806e05a20e73c",
                "sha256": "2e1a6f496bbd5a07079d1f2cb93bb487c9184c01b86d15fefb6bccf0b1237b87"
            },
            "downloads": -1,
            "filename": "python_sandboxed_evaluator-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "7c264f0aa0a66745431806e05a20e73c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 9062,
            "upload_time": "2025-01-10T05:36:09",
            "upload_time_iso_8601": "2025-01-10T05:36:09.346480Z",
            "url": "https://files.pythonhosted.org/packages/57/a1/e859de2c2b17091136e24421f8b87ea9585aa1e3eef2d4a98e2e5678f33c/python_sandboxed_evaluator-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-10 05:36:09",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "iam-mhaseeb",
    "github_project": "Python-Sandboxed-Evaluator",
    "github_not_found": true,
    "lcname": "python-sandboxed-evaluator"
}
        
Elapsed time: 1.58012s