duck.utils.codesandboxยถ

Secure Python Code Sandbox:

This script defines a class SafeCodeSandbox that provides a secure execution environment for running arbitrary Python code. It ensures isolation by:

  • Running code in a subprocess.

  • Blocking dangerous imports and built-ins.

  • Restricting system resources like CPU and memory.

  • Providing execution time and memory limits to prevent abuse.

Note:

  • This is only available for Linux environment.

Module Contentsยถ

Classesยถ

SafeCodeSandbox

Enhanced Secure Python Code Sandbox:

APIยถ

class duck.utils.codesandbox.SafeCodeSandbox[source]ยถ

Enhanced Secure Python Code Sandbox:

This class runs Python code in a highly secure, isolated environment. It blocks unsafe imports, restricts resource usage (CPU, memory), and executes the code in a subprocess with limited system call access to prevent abuse.

execute(code: str, variable_name: str)[source]ยถ

Executes the provided Python code in a secure sandbox environment and retrieves the value of a specific variable.

Parameters:
  • code โ€“ The Python code to be executed in the sandbox.

  • variable_name โ€“ The name of the variable whose value we want to retrieve.

Returns:

A dictionary with either: - โ€œsuccessโ€: the value of the specified variable. - โ€œerrorโ€: error message including full traceback if an exception occurs.

Return type:

dict

run_in_subprocess(py_code: str, variable_name: str, temp_dir: str) โ†’ dict[source]ยถ
sanitize_code(code: str) โ†’ str[source]ยถ