在Python中将大文件发送到PIPE输入

3 投票
1 回答
2090 浏览
提问于 2025-04-16 03:46

我有以下代码:

sourcefile = open(filein, "r")
targetfile = open(pathout, "w")

content= sourcefile.read():

p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)
p.communicate(content)

sourcefile.close()
targetfile.close()

源文件的数据量很大,所以把它存储在'content'里需要占用很多内存和交换空间。我尝试直接把文件发送到标准输入(stdin),用stdin=sourcefile,这样可以工作,但外部脚本却“挂起”,也就是说,它一直在等待文件结束标志(EOF)。这可能是外部脚本的一个bug,但现在我无法控制这个问题。

有没有什么建议可以把这个大文件发送给我的外部脚本呢?

1 个回答

4

p.communicate(content) 替换成一个循环,这个循环从 sourcefile 读取内容,然后分块写入 p.stdin。当 sourcefile 读取完毕(也就是到达文件末尾)时,要记得关闭 p.stdin

sourcefile = open(filein, "r")
targetfile = open(pathout, "w")

p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)
while True:
    data = sourcefile.read(1024)
    if len(data) == 0:
        break
    p.stdin.write(data)
sourcefile.close()
p.stdin.close()

p.wait()
targetfile.close()

撰写回答