python - 我可以覆盖 io.BufferedReader 中的默认 read() 方法吗?

标签 python python-3.x

我只需将文件的一部分发送到另一个进程的 STDIN 中?

#Python 3.5
from subprocess import PIPE, Popen, STDOUT

fh = io.open("test0.dat", "rb")
fh.seek(10000)
p = Popen(command, stdin=fh, stdout=PIPE, stderr=STDOUT)
p.wait()

如何确保 command 只会从 stdin 读取 1000 个以上字节,然后遇到 EOF。 我无法控制命令如何读取标准输入。

最佳答案

问题是,当传递一个句柄时,Popen 会尝试获取 fileno,并使用真正的操作系统句柄,因此不可能用其他类似文件的对象轻松欺骗它。

但是您可以将 Popen stdin 设置为 PIPE,只向其写入正确数量的字节,可能是小块,在您选择的节奏,然后关闭它

import io
from subprocess import PIPE, Popen, STDOUT

fh = io.open("test0.dat", "rb")
fh.seek(10000)


p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
p.stdin.write(fh.read(1000))
# do something & write again
p.stdin.write(fh.read(1000))
# now it's enough: close the input
p.stdin.close()

p.wait()

但要小心:由于 stdinstdout 使用 PIPE,因此您必须使用 stdout 以避免死锁.

关于python - 我可以覆盖 io.BufferedReader 中的默认 read() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920747/

相关文章:

python - 在数组的一个特定维度上执行操作

python - 矩阵乘法与按位运算符

python-3.x - 连接到 "Iex"或 "morningstar"并检索数据

python - 在 Python 'with' 语句中重用多个上下文

python - 在 macOS High Sierra 上使用 Python 3 安装 OpenCV 的问题

python - 频域 fft 后的带通滤波器

python - Pandas 数据框 : How to convert numeric columns into pairwise categorical data?

python - Python 中是否有包含函数参数的字典?

Python - 访问二维列表中命名元组的一部分

python-3.x - 谷歌云pubsub python同步拉取