Skip to content

Subprocess utils

run_subprocess_safely(command, timeout=2000)

Run a subprocess and raise an error if it fails.

Parameters:

Name Type Description Default
command str

The command to run.

required
timeout int

The timeout for the command.

2000

Returns:

Type Description
Dict[str, Any]

The result of the subprocess.

Source code in bionemo/core/utils/subprocess_utils.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def run_subprocess_safely(command: str, timeout: int = 2000) -> Dict[str, Any]:
    """Run a subprocess and raise an error if it fails.

    Args:
        command: The command to run.
        timeout: The timeout for the command.

    Returns:
        The result of the subprocess.
    """
    try:
        result = subprocess.run(shlex.split(command), capture_output=True, timeout=timeout, check=True, text=True)
        return {"stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode}
    except subprocess.TimeoutExpired as e:
        logger.error(f"Command timed out. Command: {command}\nstdout:\n{e.stdout}\nstderr:\n{e.stderr}")
        return {"error": "timeout", "stdout": e.stdout, "stderr": e.stderr, "returncode": None}

    except subprocess.CalledProcessError as e:
        logger.error(
            f"Command failed. Command: {command}\nreturncode: {e.returncode}\nstdout:\n{e.stdout}\nstderr:\n{e.stderr}"
        )
        return {"error": "non-zero exit", "stdout": e.stdout, "stderr": e.stderr, "returncode": e.returncode}

    except FileNotFoundError as e:
        logger.error(f"Command not found. Command: {command}\nstderr:\n{str(e)}")
        return {"error": "not found", "stdout": "", "stderr": str(e), "returncode": None}

    except Exception as e:
        # catch-all for other unexpected errors
        return {"error": "other", "message": str(e), "stdout": "", "stderr": "", "returncode": None}