在 python 2.7 中,此方法有效并返回预期的字符串它有效!
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())
关于Python 3 子进程管道 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830944/