Spaces:
Running
Running
File size: 1,335 Bytes
faefb1f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | from __future__ import annotations
import logging
import os
import signal
import subprocess
from typing import Dict, Any, List
_logger = logging.getLogger(__name__)
def run_subprocess(
cmd: List[str],
timeout: float,
max_output: int = 65536,
) -> Dict[str, Any]:
"""Run a subprocess with timeout handling and output capture.
Consolidates the duplicate subprocess logic from code_executor_service
and csv_analysis_service.
"""
proc = subprocess.Popen(
cmd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
stdout_bytes, stderr_bytes = proc.communicate(timeout=timeout)
timed_out = False
except subprocess.TimeoutExpired:
try:
if os.name == "nt":
proc.kill()
else:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except Exception:
proc.kill()
stdout_bytes, stderr_bytes = proc.communicate()
timed_out = True
return {
"stdout": (stdout_bytes.decode("utf-8", errors="replace")[:max_output] if stdout_bytes else ""),
"stderr": (stderr_bytes.decode("utf-8", errors="replace")[:max_output] if stderr_bytes else ""),
"exit_code": proc.returncode,
"timed_out": timed_out,
}
|