I want to write a function that will execute multiple shell commands one at a time and print what the shell returns in real time.
I currently have the following code which does not print the shell (I am using Windows 10 and python 3.6.2):
commands = ["foo", "foofoo"]
p = subprocess.Popen("cmd.exe", shell=True, stdin=subprocess.PIPE, \
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for command in commands:
p.stdin.write((command + "\n").encode("utf-8"))
p.stdin.close()
p.stdout.read()
How can I see what the shell returns in real time ?
Edit : This question is not a duplicate of the two first links in the comments, they do not help printing in real time.
Assuming you want control of the output in your python code you might need to do something like this
I believe you need something like this
It is possible to handle
stdin
andstdout
in different threads. That way one thread can be handling printing the output fromstdout
and another one writing new commands onstdin
. However, sincestdin
andstdout
are independent streams, I do not think this can guarantee the order between the streams. For the current example it seems to work as intended, though.Also, note that I am writing
stdout
line by line, which is normally OK, since it tends to be buffered and being generated a line (or more) at a time. I guess it is possible to handle an unbufferedstdout
stream (or e.g.stderr
) character-by-character instead, if that is preferable.