import subprocess

from mower import __system__
from mower.utils.log import logger


def subprocess_run(cmd, timeout=10):
    """
    Args:
        cmd (list):
        timeout (int):

    Returns:
        str:
    """
    logger.debug(f"Execute: {cmd}")
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        shell=False,
        creationflags=subprocess.CREATE_NO_WINDOW if __system__ == "windows" else 0,
    )
    try:
        stdout, stderr = process.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        process.kill()
        stdout, stderr = process.communicate()
        logger.warning(
            f"TimeoutExpired when calling {cmd}, stdout={stdout}, stderr={stderr}"
        )
    return stdout.decode("utf-8")
