I'm trying to write a wrapper for a bash session using python. The first thing I did was just try to spawn a bash process, and then try to read its output. like this:
from subprocess import Popen, PIPE
bash = Popen("bash", stdin = PIPE, stdout = PIPE, stderr = PIPE)
prompt = bash.stdout.read()
bash.stdin.write("ls\n")
ls_output = bash.stdout.read()
But this does not work. First, reading from bash's stdout after creating the process fails, and when I try to write to stdin, I get a broken pipe error. What am I doing wrong?
Just to clarify again, I'm not interested in running a single command via bash and then retrieving its output, I want to have a bash session running in some process with which I can communicate via pipes.
This works:
import subprocess
command = "ls"
p = subprocess.Popen(command, shell=True, bufsize=0, stdout=subprocess.PIPE, universal_newlines=True)
p.wait()
output = p.stdout.read()
p.stdout.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With