Python 3 子进程管道 block

标签 python python-3.x subprocess

在 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/

相关文章:

python - 对多行执行函数

python - VSCode 无法将 jupyter notebook 导出到 html

python - subprocess.Popen 系统属性 arg 中的空格

python-3.x - Python - 计算数据框列的标准偏差(行级)

python 检查输出查找命令不起作用

python - 从另一个 Python 进程调用操作系统的 Python 可执行文件

python - 如何在 python selenium-webdriver 中获取标题

python - 用于表示美元金额的最佳 django 模型字段是什么?

python - None 的 numpy 索引切片

python - MatplotLib 3.0.1 中 ax.set_xlabel() 和 ax.xaxis.set_label() 的区别