Python 3 个子进程管道块

Python 3 subprocess pipe blocks

在 python 2.7 中,这有效并且 returns 预期的字符串 it works!

process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write('echo it works!\n')
print process.stdout.readline()

当我知道在 python 3.4 中尝试这个时,它卡在了 readline 命令

process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write(bytes('echo it works!\n','UTF-8'))
print(process.stdout.readline().decode('UTF-8'))

关于缓冲的提示很有帮助。在Subprocess库模块文档中可以找到以下信息:

bufsize will be supplied as the corresponding argument to the open() function when creating the stdin/stdout/stderr pipe file objects:

0 means unbuffered (read and write are one system call and can return short)

1 means line buffered (only usable if universal_newlines=True i.e., in a text mode)

If universal_newlines is False the file objects stdin, stdout and stderr will be opened as binary streams, and no line ending conversion is done.

If universal_newlines is True, these file objects will be opened as text streams in universal newlines mode using the encoding returned by locale.getpreferredencoding(False)

将它们放在一起得到以下 Python3 代码:

import subprocess
process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True)
process.stdin.write('echo it works!\n')
print(process.stdout.readline())