[Python] Managing a subprocess through a class [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to keep a subprocess alive, so that I can interact with it later.

    So far, I've tried to make the subprocess an attribute of a class, and have methods to interact with it. However, this doesn't seem to work.

    I've seen a related case in here, but I was expecting some upgrades in the subprocess library in the last years. Also, I'm actively avoiding pexpect for reasons related to the place I work at.

    I would expect to have a persistent background shell session (with several environmental variables set only in that shell) that allows me to run commands and programs, and gets closed only when I call a specific method. The output should go into a log file.

    Can someone please tell me what I'm doing wrong?

    from subprocess import Popen, PIPE
    import time

    class Session:

    def __init__(
    self,
    first_commands : list
    ):
    self._log = open("session.log", "w")
    self._proc = Popen(
    first_commands,
    stdin=PIPE,
    stdout=self._log,
    stderr=PIPE,
    universal_newlines=True,
    shell=True
    )

    def send(self, new_command : str):
    self._proc.stdin.write(new_command)
    self._proc.stdin.flush()

    def close(self):
    self._proc.stdin.write("echo Bye bye!")
    self._proc.stdin.flush()
    self._proc.kill()
    self._log.close()

    if __name__ == "__main__":
    sass = Session(["echo 'So it begins!'"])
    sass.send("pwd")
    time.sleep(2)
    sass.send("ls")
    sass.send("touch eternity.end")
    sass.send("mkdir LookWhatICreated")
    sass.close()

    Continue reading...

Compartilhe esta Página