代码之家  ›  专栏  ›  技术社区  ›  user3116130

Popen中的缓冲区有限[重复]

  •  3
  • user3116130  · 技术社区  · 11 年前

    我正在使用python代码启动一个脚本。该代码应启动脚本,在磁盘上写入文件,并等待脚本完成。

    但是每当我使用python启动这个脚本时,结果文件不超过65768字节,脚本不再响应。下面是我在python中使用的内容:

    p = subprocess.Popen(command, 
                         shell=True, 
                         stdout=subprocess.PIPE, 
                         stderr=subprocess.STDOUT, 
                         bufsize=-1)
    p.wait()
    

    其中command是脚本的命令。

    有人知道这个问题的解决方案吗?

    非常感谢。

    1 回复  |  直到 11 年前
        1
  •  2
  •   Torxed    11 年前
    from time import sleep
    p = subprocess.Popen(command, 
                         shell=True, 
                         stdout=subprocess.PIPE, 
                         stderr=subprocess.STDOUT, 
                         bufsize=-1)
    output = ''
    while p.poll() is None:
        output += p.stdout.readline()+'\n'  # <--- This is your magic
        sleep(0.025)
    output += p.stdout.read() # <--- And this is just to get the leftover data
    print('Command finished')
    
    p.stdout.close()
    

    正如@J.F对几乎每一张单曲的评论 Popen 我给出的答案,你永远不应该定义 stdout=... , stdin=... stderr=... 除非你要把它们数字化。 因为它们会填满缓冲区并挂起应用程序。

    但如果你这样做了,请确保你每隔一段时间就从中“轻敲”一次。