I have a script that writes a bunch of new files to a directory. After every file it writes, I want to print the results of an ls command. The issue is, if I call
import subprocess
p = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
print ''.join(p.stdout.readlines())
Then eventually (after having written many files) there is an "OSError: [Errno 12] cannot allocate memory" thrown by the line
p = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
because subprocess is calling os.fork() internally, which doubles the memory currently in use.
As suggested by another stack overflow (https://stackoverflow.com/a/13329386), we should be able to fix this by initializing a single Popen object at the beginning of the script, then spawning child processes as needed. However, when I do
p = subprocess.Popen(['ls'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while True:
p.stdin.write('ls')
print p.stdout.readlines()
An "IOError: [Errno 32] Broken pipe" is thrown at the first p.stdin.write('ls'), because the process has already finished executing and the input pipe was closed.
Any thoughts on how to achieve this?