Skip to content

Instantly share code, notes, and snippets.

@digi604
Created March 20, 2023 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digi604/143e4e6b0d77cb947df34a372de56ef1 to your computer and use it in GitHub Desktop.
Save digi604/143e4e6b0d77cb947df34a372de56ef1 to your computer and use it in GitHub Desktop.
import pexpect
class BashProcess:
"""A class for running persistent bash processes."""
def __init__(self):
self.shell = pexpect.spawn('/bin/bash', encoding='utf-8', timeout=300)
self.shell.expect_exact('$')
self.shell.sendline("\n")
self.shell.expect_exact('$')
self.remove = str(self.shell.before).strip()
def run(self, command):
if command == "exit":
self.shell.close()
self.shell = pexpect.spawn('/bin/bash', encoding='utf-8', timeout=300)
self.shell.expect_exact('$')
return "Shell restarted."
commands = command.split('\n')
output = ""
for cmd in commands:
self.shell.sendline(cmd)
self.shell.expect_exact('$')
output += str(self.shell.before).strip().replace(self.remove, "$ ")
return output
def bash_terminal():
bash = BashProcess()
return bash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment