I've got a script parent.py
trying to to read stdout from a subprocess sub.py
in Python.
The parent parent.py
:
#!/usr/bin/python
import subprocess
p = subprocess.Popen("sub.py", stdout=subprocess.PIPE)
print p.stdout.read(1)
And the subprocess, sub.py
:
#!/usr/bin/python
print raw_input( "hello world!" )
I would expect running parent.py
to print the 'h' from "hello world!". Actually, it hangs. I can only get my expected behaviour by adding -u
to sub.py
's she-bang line.
This confuses me because the -u
switch makes no difference when sub.py
is run directly from a shell; the shell is somehow privy to the un-flushed output stream, unlike parent.py
.
My goal is to run a C program as the subprocess, so I won't be able to control whether or not it flushes stdout. How is it that a shell has better access to a process's stdout than Python running the same thing from subprocess.Popen
? Am I going to be able to read such a stdout stream from a C program that doesn't flush its buffers?
EDIT:
Here is an updated example based on korylprince's comment...
## capitalize.sh ##
#!/bin/sh
while [ 1 ]; do
read s
echo $s | tr '[:lower:]' '[:upper:]'
done
########################################
## parent.py ##
#!/usr/bin/python
from subprocess import Popen, PIPE
# cmd = [ 'capitalize.sh' ] # This would work
cmd = [ 'script', '-q', '-f', '-c', 'capitalize.sh', '/dev/null']
p = Popen(cmd, stdin=PIPE)
p.stdin.write("some string\n")
p.wait()
When running through script
, I get steady printing of newlines (and if this were a Python, subprocess, it'd raise an EOFerror).