Python subprocess.Popen文件中的stdin,将内容更改为流

时间:2015-05-28 08:13:39

标签: python mysql subprocess stdin

我有一个大文本文件(MySQL数据库转储),我想读入我的MySQL服务器,但我需要更改文本。我不想将整个文件读入内存,所以我想到流式文件并在需要时更改行。

我有以下代码:

p = sp.Popen(['/usr/local/bin/mysql', '-u', 'root'], stdin=sp.PIPE)
with open(unzipped_path, 'rb', buffering=0) as infile:
    for line in infile:
        text = line.replace('foo', 'bar')
        p.communicate(input=text)

我收到错误ValueError: I/O operation on closed file。有没有更简单的方法来执行此操作?

1 个答案:

答案 0 :(得分:1)

p.communicate(input=text)启动该过程,发送文本并终止它。

当循环尝试发送第二行时,没有剩余的进程可以与之交谈。

使用

for line in infile:
    text = line.replace('foo', 'bar')
    p.stdin.write(text)

p.stdin.close()
p.wait()

请注意,我不确定迭代文件是否会保留换行符;你可能需要手动发送它们。