un-inception/clients/python/async/examples/concurrent_execution.py
russell@unturf.com 35bbd37877 fix: CI validation scripts and example exit codes
lint-all-sdks.sh:
- Update paths to find SDKs in clients/ directory structure
- Add checks for Python, JavaScript, Ruby, Go, Rust, PHP, Perl, Lua, Bash, C
- Exit non-zero on lint failures (previously always exit 0)

validate-examples.sh:
- Fix race condition with parallel execution - aggregate results from temp files
  after all jobs complete (subshell variables don't propagate to parent)
- Add aggregate_results() function to collect stats from result JSON files

Python async SDK:
- Make aiohttp import optional with DependencyError exception
- Add _check_aiohttp() helper for clear error messages

Python examples (async + sync):
- Exit with code 0 when API keys missing (CI-friendly skip)
- Change "Error:" to "Skipping:" for missing credentials
- Wrap un_async imports in try/except for aiohttp ImportError
2026-02-07 18:01:51 -05:00

66 lines
1.9 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"))
try:
from un_async import execute_code
except ImportError as e:
print(f"Missing dependency: {e}")
print("Install with: pip install aiohttp")
sys.exit(0) # Exit gracefully for CI
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)