Source code for ewoksmx.shell_utils.execute_local
import os
import pathlib
import subprocess
from typing import List
from typing import Union
from .execute_results import BashExecutionResult
[docs]
def execute_bash_commands(
shell_commands: List[str],
working_directory: Union[str, pathlib.Path],
stdout: bool = True,
stderr: bool = True,
stdmerge: bool = True,
name: str = "run",
) -> BashExecutionResult:
"""Execute bash shell commands and capture output in files."""
working_directory = pathlib.Path(working_directory)
working_directory.mkdir(parents=True, exist_ok=True)
script_path = working_directory / f"{name}.sh"
result = BashExecutionResult(
script_path, stdout=stdout, stderr=stderr, stdmerge=stdmerge
)
with open(script_path, "w") as script_file:
script_file.write("#!/bin/bash -l\n\n")
script_file.write("set -e\n\n")
if result.log_path:
script_file.write(f"exec > {result.log_path} 2>&1\n\n")
elif result.stdout_path and result.stderr_path:
script_file.write(
f"exec > {result.stdout_path} 2> {result.stderr_path}\n\n"
)
elif result.stdout_path:
script_file.write(f"exec > {result.stdout_path}\n\n")
elif result.stderr_path:
script_file.write(f"exec 2> {result.stderr_path}\n\n")
script_file.writelines(f"{cmd}\n" for cmd in shell_commands)
os.chmod(script_path, 0o755)
result.return_code = subprocess.run([script_path], cwd=working_directory).returncode
return result