A reusable package for executing Python code in Docker containers and extracting charts/images
Project description
Codibox - Safe Code Execution Package
A reusable Python package for executing code in Docker containers and extracting charts/images.
🎯 Purpose
This package extracts the core functionality of executing Python code in Docker and extracting results. It's designed to be:
- Reusable across different projects
- Configurable for different use cases
- Standalone - works independently
- Well-tested and documented
📦 Installation
# Install as package
pip install -e ./codibox
# Or use directly
import sys
sys.path.insert(0, './codibox')
from codibox import DockerCodeExecutor
🚀 Quick Start
Basic Usage
from codibox import DockerCodeExecutor
# Initialize executor
executor = DockerCodeExecutor(container_name="sandbox")
# Execute code
result = executor.execute(
code="""
import matplotlib.pyplot as plt
import pandas as pd
# Create sample data
data = [1, 2, 3, 4, 5]
# Create chart
plt.figure(figsize=(10, 6))
plt.plot(data)
plt.title('Sample Chart')
plt.savefig('temp_code_files/chart.png')
plt.show()
"""
)
# Check results
if result.success:
print("✅ Execution successful!")
print(f"📊 Found {len(result.images)} images")
print(f"📄 Markdown length: {len(result.markdown)} characters")
# Access images
for img_path in result.images:
print(f" - {img_path}")
else:
print(f"❌ Execution failed: {result.stderr}")
With Input Files
executor = DockerCodeExecutor(container_name="sandbox")
result = executor.execute(
code="""
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
plt.hist(df['age'], bins=20)
plt.savefig('temp_code_files/age_distribution.png')
plt.show()
""",
input_files=["datasets/customer_data.csv"]
)
Process Images
from codibox import ImageProcessor
# Execute code
result = executor.execute(code="...")
# Process images
processor = ImageProcessor()
markdown_with_images = processor.process_markdown(result.markdown)
# Or get all images as HTML
images_html = processor.get_all_images_html()
📋 API Reference
DockerCodeExecutor
__init__(container_name, host_temp_dir, image_output_dir, timeout, cleanup_on_error, auto_setup)
Initialize the executor.
Parameters:
container_name(str): Docker container name (default: "sandbox")host_temp_dir(str): Host temp directory (default: "/tmp")image_output_dir(str): Image directory in container (default: "temp_code_files")timeout(int, optional): Execution timeout in seconds (default: 300)cleanup_on_error(bool): Cleanup on error (default: True)auto_setup(bool): Automatically set up container if not running (default: False)
execute(code, input_files, working_dir) -> ExecutionResult
Execute Python code in Docker.
Parameters:
code(str): Python code to executeinput_files(List[str], optional): Input files to copy to containerworking_dir(str, optional): Working directory in container
Returns:
ExecutionResultwith:markdown: Execution markdown outputsuccess: Whether execution succeededimages: List of image file pathscsv_files: List of generated CSV filesstdout: Standard outputstderr: Standard errorexecution_time: Execution time in seconds
check_container() -> bool
Check if Docker container is running.
get_container_status() -> Dict[str, Any]
Get detailed status of the Docker container.
Returns:
- Dictionary with:
exists,running,status,image
setup_container(image_name, force_rebuild) -> bool
Set up the Docker container by building the image and starting the container.
Parameters:
image_name(str): Docker image name (default: "python_sandbox:latest")force_rebuild(bool): Rebuild image even if it exists (default: False)
Returns:
Trueif setup successful,Falseotherwise
start_container() -> bool
Start an existing Docker container.
Returns:
Trueif started successfully,Falseotherwise
stop_container() -> bool
Stop the Docker container.
Returns:
Trueif stopped successfully,Falseotherwise
ensure_container_running() -> bool
Ensure the container is running. If not, try to start it or set it up.
Returns:
Trueif container is running,Falseotherwise
ImageProcessor
__init__(image_base_dir)
Initialize image processor.
find_images() -> List[str]
Find all image files in base directory.
process_markdown(markdown) -> str
Replace markdown image references with HTML.
get_image_html(image_path) -> str
Get HTML for a specific image.
🔧 Configuration
Custom Container
executor = DockerCodeExecutor(
container_name="my_custom_container",
host_temp_dir="/custom/tmp",
image_output_dir="charts"
)
Timeout Settings
executor = DockerCodeExecutor(
container_name="sandbox",
timeout=600 # 10 minutes
)
📊 Use Cases
1. Chart Generation Service
class ChartService:
def __init__(self):
self.executor = DockerCodeExecutor()
def generate_chart(self, code: str, data_file: str = None):
files = [data_file] if data_file else []
result = self.executor.execute(code, input_files=files)
return result
2. Code Testing Framework
def test_code(code: str, expected_images: int = 1):
executor = DockerCodeExecutor()
result = executor.execute(code)
assert result.success, f"Code failed: {result.stderr}"
assert len(result.images) >= expected_images
return result
3. Batch Processing
def process_multiple_codes(codes: List[str]):
executor = DockerCodeExecutor()
results = []
for code in codes:
result = executor.execute(code)
results.append(result)
return results
✅ Advantages of This Approach
- Isolation: Code runs in isolated Docker container
- Security: No network access, limited resources
- Reproducibility: Same environment every time
- Image Extraction: Automatic chart discovery
- Error Handling: Graceful fallbacks
- Reusability: Works across different projects
🎯 Is This Approach Good?
✅ Pros:
- Security: Isolated execution prevents malicious code
- Consistency: Same environment for all executions
- Image Capture: Notebook execution captures matplotlib outputs
- Flexibility: Can handle any Python code
- Error Recovery: Can fallback to direct Python execution
⚠️ Considerations:
- Performance: Docker overhead (1-2 seconds per execution)
- Resource Usage: Container needs to stay running
- Dependencies: Requires Docker and container setup
- Network Isolation: Code can't make API calls (by design)
💡 Improvements Possible:
- Caching: Cache execution results for identical code
- Parallel Execution: Run multiple codes in parallel
- Resource Limits: Better memory/CPU limits
- Streaming: Stream output as it executes
- Metrics: Track execution times and success rates
🔄 Migration Guide
From Current Code
Before:
from agent_coder.agents import CodeExecutor
executor = CodeExecutor()
result, success, csv_files = executor._execute_code(code, filename)
After:
from codibox import DockerCodeExecutor
executor = DockerCodeExecutor()
result = executor.execute(code, input_files=[filename])
# result.markdown, result.success, result.csv_files
📝 Examples
See examples/ directory for complete usage examples:
basic_usage.py- Simple code execution examplesai_analyst/streamlit_chart_generator.py- Complete Streamlit dashboard applicationREADME.md- Detailed examples documentationsetup_example.sh- Quick setup script for examples
Quick Start with Examples
# Setup Docker container
cd examples
./setup_example.sh
# Run basic examples
python basic_usage.py
# Run Streamlit app
cd examples/ai_analyst
streamlit run streamlit_chart_generator.py
See examples/README.md for full documentation.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file codibox-1.0.1.tar.gz.
File metadata
- Download URL: codibox-1.0.1.tar.gz
- Upload date:
- Size: 16.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f88217160b1e9a7e58ce04ca0dee8bbc436311c850f7e237d34a7cc414b0dd77
|
|
| MD5 |
736f8e37f830431a4293258152f65777
|
|
| BLAKE2b-256 |
6eb31c85bc2a46a8dd31db63c765be1916a05243c5fa0dd272f8ae4d41a4b952
|
File details
Details for the file codibox-1.0.1-py3-none-any.whl.
File metadata
- Download URL: codibox-1.0.1-py3-none-any.whl
- Upload date:
- Size: 16.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d567295966e468b3ca4018a473e013846b18e0760c20026fa39df117b829fbce
|
|
| MD5 |
935574291df1cda02d8ef96549fd654a
|
|
| BLAKE2b-256 |
9b43898ff320bd5299872d5e78acfc1507b1d17a0e9ee9886f0de37c3766c564
|