difference between communicate() and .stdin.write, .stdout.read or .stderr.read - python

余生长醉 提交于 2019-12-05 21:19:05

The external process you've spawned may block forever if you are using process.stdin.write without any awareness of possible buffering issues. For example, if the process responds to your 1-line input by writing to its stdout a large (say, 10-100MB) amount of data and you continue to write to its stdin while not receiving this data, than the process will become blocked on write to stdout (stdout is an unnamed pipe and the OS maintains buffers of a particular size for them).

You can try the iterpipes library that deals with these issues by running input and ouput tasks as separate threads.

communicate is designed to prevent a deadlock that wouldn't occur in your application anyway: it is there primarily for the situation where both stdin and stdout on a Popen object are pipes to the calling process, i.e.

subprocess.Popen(["sometool"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

In your case, you can safely read from cut.stdout. You may use communicate if you find it convenient, but you don't need to.

(Note that subprocess.Popen("/etc/passwd") doesn't make sense; you seem to have forgotten a cat. Also, don't forget shell=True.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!