feat: first commit
This commit is contained in:
38
shell.py
Normal file
38
shell.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Persistent shell session manager."""
|
||||
|
||||
import subprocess
|
||||
|
||||
|
||||
class ShellSession:
|
||||
"""Wraps a persistent bash subprocess."""
|
||||
|
||||
_SENTINEL = "__END_OF_CMD_OUTPUT__"
|
||||
|
||||
def __init__(self, cwd: str) -> None:
|
||||
self._proc = subprocess.Popen(
|
||||
["bash"],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
cwd=cwd,
|
||||
text=True,
|
||||
)
|
||||
|
||||
def run(self, cmd: str) -> str:
|
||||
"""Send a command and return its output."""
|
||||
full_cmd = f"{cmd}\necho {self._SENTINEL}\n"
|
||||
self._proc.stdin.write(full_cmd)
|
||||
self._proc.stdin.flush()
|
||||
lines = []
|
||||
for line in self._proc.stdout:
|
||||
if self._SENTINEL in line:
|
||||
break
|
||||
lines.append(line)
|
||||
return "".join(lines)
|
||||
|
||||
def close(self) -> None:
|
||||
"""Terminate the shell process."""
|
||||
if self._proc.poll() is None:
|
||||
self._proc.stdin.close()
|
||||
self._proc.terminate()
|
||||
self._proc.wait()
|
||||
Reference in New Issue
Block a user