subprocess and stdin.write(), stdout.read()

Tobiah toby at tobiah.org
Tue Mar 24 15:08:24 EDT 2015


The docs for the subprocess.Popen() say:

	Use communicate() rather than .stdin.write, .stdout.read
	or .stderr.read to avoid deadlocks due to any of the other
	OS pipe buffers filling up and blocking the child process

But if I want to send a string to stdin, how can I do that without
stdin.write()?

This seems to work:

import subprocess as s

thing = """
         hey
         there
         foo man is here
         hey foo
         man is there
         so foo
"""
p = s.Popen(['grep', 'foo'], stdin = s.PIPE, stdout = s.PIPE)
p.stdin.write(thing)
print p.communicate()

######################

('\they foo\n \tfoo there\n', None)


Will this always avoid the deadlock problem?

This also works:

p = s.Popen(['grep', 'foo'], stdin = s.PIPE, stdout = s.PIPE)
p.stdin.write(thing)
p.stdin.close()
print p.stdout.read()

Is that vulnerable to deadlock?  Is there a better way
to write to and read from the same process?

Thanks!

Tobiah



More information about the Python-list mailing list