1

我在 RHEL 6.5 上使用 subprocess32 3.2.6 和 Python 2.6.6。一个像这样的序列:

command = "sleep 20"

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

std_out, std_err = proc.communicate(None, timeout=1)

按预期工作,即一秒超时有效。然而,如果

command = "sleep 20; echo Hello World"

子进程似乎运行了整个 20 秒。我可以解决这个问题,但最好了解我做错了什么或为什么它会以这种方式工作。顺便说一句,这是在一个非常受控、受信任的环境中,所以“shell=True”没有风险。

4

1 回答 1

0

我尝试了一切,只需使用这个:

def reader(f,buffer):
   while True:
     line=f.readline()
     if line:
        buffer.append(line)
     else:
        break


command = subprocess.Popen (cmd, shell=True, stdout=subprocess.PIPE,
                                                stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
                    command.stdin.write (bytearray(testin, 'utf8'))
                    command.stdin.close ()
                    print ('Writing i/p')
                    linebuffer = []
                    t = Thread (target=reader, args=(command.stdout, linebuffer))
                    t.daemon = True
                    t.start ()

                    start = time.time ()
                    while start + timeout > time.time ():
                        if linebuffer:
                            ans += linebuffer.pop ()
于 2017-07-12T06:22:46.583 回答