Executes bash commands and returns the output.
| 26 | return pexpect |
| 27 | |
| 28 | class BashProcess: |
| 29 | """Executes bash commands and returns the output.""" |
| 30 | |
| 31 | def __init__( |
| 32 | self, |
| 33 | strip_newlines: bool = False, |
| 34 | return_err_output: bool = False, |
| 35 | persistent: bool = False, |
| 36 | ): |
| 37 | """Initialize with stripping newlines.""" |
| 38 | self.strip_newlines = strip_newlines |
| 39 | self.return_err_output = return_err_output |
| 40 | self.prompt = "" |
| 41 | self.process = None |
| 42 | if persistent: |
| 43 | self.prompt = str(uuid4()) |
| 44 | self.process = self._initialize_persistent_process(self.prompt) |
| 45 | |
| 46 | @staticmethod |
| 47 | def _initialize_persistent_process(prompt: str) -> pexpect.spawn: |
| 48 | # Start bash in a clean environment |
| 49 | # Doesn't work on windows |
| 50 | pexpect = _lazy_import_pexpect() |
| 51 | process = pexpect.spawn( |
| 52 | "env", ["-i", "bash", "--norc", "--noprofile"], encoding="utf-8" |
| 53 | ) |
| 54 | # Set the custom prompt |
| 55 | process.sendline("PS1=" + prompt) |
| 56 | |
| 57 | process.expect_exact(prompt, timeout=10) |
| 58 | return process |
| 59 | |
| 60 | def run(self, commands: Union[str, List[str]]) -> str: |
| 61 | """Run commands and return final output.""" |
| 62 | print("entering run") |
| 63 | if isinstance(commands, str): |
| 64 | commands = [commands] |
| 65 | commands = ";".join(commands) |
| 66 | print(commands) |
| 67 | if self.process is not None: |
| 68 | return self._run_persistent( |
| 69 | commands, |
| 70 | ) |
| 71 | else: |
| 72 | return self._run(commands) |
| 73 | |
| 74 | def _run(self, command: str) -> str: |
| 75 | """Run commands and return final output.""" |
| 76 | print("entering _run") |
| 77 | try: |
| 78 | output = subprocess.run( |
| 79 | command, |
| 80 | shell=True, |
| 81 | check=True, |
| 82 | stdout=subprocess.PIPE, |
| 83 | stderr=subprocess.STDOUT, |
| 84 | ).stdout.decode() |
| 85 | except subprocess.CalledProcessError as error: |
no outgoing calls
no test coverage detected