Run Python Code
Execute Python code securely in isolated sandboxes.
sandbox.run(
code: str,
timeout: int = 10000,
language: str = "python"
) -> RunResultParameters
codestringrequiredPython code to execute. Can be a single line or multi-line script.
timeoutintTimeout in milliseconds. Defaults to 10000ms (10 seconds).
languagestringProgramming language to use. Currently only "python" is supported. Default value is "python".
Returns
stdoutstrStandard output from the code execution.
stderrstrStandard error from the code execution.
returncodeintExit code from the execution (0 = success, non-zero = error).
codestrThe original code that was executed.
languagestrThe language that was executed (currently only "python").
Examples
Basic Example
from concave import Sandbox
sbx = Sandbox.create()
result = sbx.run("print('Hello from Python!')")
print(result.stdout) # Hello from Python!
sbx.delete()Multi-Line Code
from concave import Sandbox
sbx = Sandbox.create()
code = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
"""
result = sbx.run(code)
print(result.stdout) # 55
sbx.delete()Error Handling
from concave import Sandbox
sbx = Sandbox.create()
result = sbx.run("print(1/0)")
if result.returncode != 0:
print(f"Error: {result.stderr}")
else:
print(result.stdout)
sbx.delete()Exceptions
SandboxValidationErrorExceptionRaised when the code is empty or language is unsupported.
SandboxNotFoundErrorExceptionRaised when the sandbox no longer exists.
SandboxTimeoutErrorExceptionRaised when code execution exceeds the timeout duration.
SandboxConnectionErrorExceptionRaised when unable to connect to the sandbox service.