un-inception/clients/python/async/examples/concurrent_execution.py
russell@unturf.com 1e01d09883 feat: per-client Makefile infrastructure for 4-mode testing
Add per-client Makefiles for C, Python, and Go with:
- CLI mode: Tests --help, arg parsing, syntax validation
- Library mode: Unit tests, import verification
- Integration mode: API contract validation (with credentials)
- Functional mode: Real-world scenario tests

C client:
- 22 library tests (SHA-256, HMAC-SHA256, detect_language)
- Full unsandbox.c implementation with examples

Python client (sync + async):
- Delegates to sync/ and async/ subdirectories
- pytest-based test suites with coverage
- Examples for concurrent execution, streaming

Go client:
- Delegates to sync/ and async/ subdirectories
- go test integration with vet and fmt

Also update detect-changes.sh to detect changes in
both root-level un.* files AND clients/ directory.
2026-01-15 16:39:56 -05:00

61 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""
Concurrent execution example - demonstrates async capabilities
This example shows how to:
1. Execute multiple code snippets concurrently
2. Use asyncio.gather() to wait for all results
3. Handle multiple async operations efficiently
Usage:
python concurrent_execution.py
Or with custom credentials:
UNSANDBOX_PUBLIC_KEY=... UNSANDBOX_SECRET_KEY=... python concurrent_execution.py
"""
import asyncio
import sys
import os
# Add src to path for development
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from un_async import execute_code
async def run_code(language: str, code: str, name: str):
"""Execute code and return result with a name."""
print(f"[{name}] Starting execution...")
result = await execute_code(language, code)
output = result.get("stdout", "").strip()
print(f"[{name}] Result: {output}")
return {"name": name, "result": result}
async def main():
"""Execute multiple code snippets concurrently."""
tasks = [
run_code("python", 'print("Hello from Python")', "python_hello"),
run_code("javascript", 'console.log("Hello from JavaScript")', "js_hello"),
run_code("bash", 'echo "Hello from Bash"', "bash_hello"),
run_code("python", 'import math; print(f"pi = {math.pi:.4f}")', "python_math"),
]
try:
print("Running 4 concurrent code executions...\n")
results = await asyncio.gather(*tasks)
print("\n=== Execution Summary ===")
for result in results:
print(f"{result['name']}: OK")
return 0
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
exit_code = asyncio.run(main())
sys.exit(exit_code)