code-executor-py
A powerful and flexible Python module for secure code execution in isolated environments. Execute Python code safely in virtual environments locally or in remote sandbox containers.
Features
-
VenvExecutor: Execute code in isolated virtual environments
- Automatic dependency detection and installation
- Smart package name resolution
- Handles import errors intelligently
-
RemoteExecutor: Run code in remote sandbox containers
- Client-server architecture
- Secure data serialization
- Network-isolated execution
-
Scoped Environment Variables
- Pass per-function environment values during
create_executable - Variables are available only to that execution context
- Pass per-function environment values during
-
Smart Package Management
- Automatically resolves import statements to package names
- Maps common aliases to correct package names (e.g., 'sklearn' → 'scikit-learn')
- Dynamically installs missing dependencies
Installation
pip install code-executor-py
Quick Start
Local Execution with VenvExecutor
import pandas as pd
from code_executor_py import VenvExecutor
# Define your function
func_code = """
from sklearn.preprocessing import StandardScaler
import pandas as pd
def process_data(data_df):
scaler = StandardScaler()
return pd.DataFrame(scaler.fit_transform(data_df), columns=data_df.columns)
"""
# Create executor and compile function
executor = VenvExecutor()
process_data = executor.create_executable(
func_code,
env_vars={"DATA_API_KEY": "abc123"}
)
# Execute function with data
test_data = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
result = process_data(data_df=test_data)
print(result)
Remote Execution (Server)
from code_executor_py import RemoteExecutorServer
# Start a server on port 8099
server = RemoteExecutorServer(host="0.0.0.0", port=8099)
server.run()
Remote Execution (Client)
from code_executor_py import RemoteExecutor
# Connect to the remote server
executor = RemoteExecutor("http://localhost:8099")
# Define your function
func_code = """
def add_numbers(a: int, b: int) -> int:
return a + b
"""
# Create executable function
add_numbers = executor.create_executable(
func_code,
env_vars={"REMOTE_SECRET": "secret-value"}
)
# Execute remotely
result = add_numbers(5, 3)
print(result) # Output: 8
Advanced Usage
Using with LLMs to Auto-Install Dependencies
from code_executor_py import VenvExecutor
from langchain_openai import ChatOpenAI
# Create executor with LLM for smart package resolution
executor = VenvExecutor(
llm=ChatOpenAI(temperature=0),
debug_mode=True
)
# The executor can now ask the LLM for the correct package name
# when encountering unknown imports
Scoped Environment Variables
from code_executor_py import VenvExecutor
executor = VenvExecutor()
secret_function = executor.create_executable(
"""
import os
def get_secret():
return os.environ.get("MY_SECRET")
""",
function_name="get_secret",
env_vars={"MY_SECRET": "top-secret"}
)
print(secret_function()) # -> "top-secret"
Environment variables provided in env_vars are injected only into the spawned
subprocess and never touch the parent process.
Custom Base Packages
from code_executor_py import VenvExecutor
# Create executor with custom base packages
executor = VenvExecutor(
venv_path="./custom_venv",
base_packages=["numpy", "pandas", "matplotlib", "scipy"]
)
How It Works
- Code Analysis: Your function code is analyzed to extract imports
- Environment Preparation: Dependencies are automatically installed in isolated environments
- Secure Execution: Code runs in a separate process with proper error handling
- Result Serialization: Results are properly serialized and returned to your main program
Security Benefits
- Isolation: Code executes in separate environments, protecting your main application
- Dependency Management: Avoid conflicts with your application's dependencies
- Resource Control: Limit the resources available to executed code (especially with remote execution)
- Network Isolation: Remote execution provides complete network isolation
Use Cases
- AI/ML Pipelines: Safely execute generated or user-provided code
- Data Processing: Run data transformation scripts in isolation
- Teaching/Education: Create safe execution environments for student code
- Microservices: Execute code remotely for resource-intensive operations
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request or open an Issue.
Author
Metadata
Release files for code-executor-py 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| code_executor_py-0.3.0.tar.gz | 10.3 kB | Without provenance | Details for code_executor_py-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| code_executor_py-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for code_executor_py-0.3.0-py3-none-any.whl |
Total release size: 19.9 kB
Release files / code_executor_py-0.3.0.tar.gz
| Download URL | code_executor_py-0.3.0.tar.gz |
|---|---|
| Size | 10.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a847cda01a469ce73b7912c227df9adb05b95a012b5e595a8b437e5c95d2c89d
|
|
BLAKE2b-256 checksum How to use checksums |
80b41dd6724020b651aad2c7177d4fc5797b8ea0b9bdc7e1dcaed8a7b660c906
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.7
|
Release files / code_executor_py-0.3.0-py3-none-any.whl
| Download URL | code_executor_py-0.3.0-py3-none-any.whl |
|---|---|
| Size | 9.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ac1cffac84d689a589718fc5a30e89ab88e6019647b129a8b7cd86fff66302d9
|
|
BLAKE2b-256 checksum How to use checksums |
c2e4a1d999bb7267c03d69520921d97b47b9d2c30c1d78254194c0f30190bb21
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.7
|
Security for code-executor-py 0.3.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.