1

在下面我的 python 脚本的片段中,我认为 temp2 不会等待 temp 完成运行,输出可能很大,但只是文本。这会从 temp 中截断结果('out'),它会在中线停止。'out' from temp 工作正常,直到添加 temp 2。我尝试添加 time.wait() 以及 subprocess.Popen.wait(temp)。这些都允许 temp 运行到完成,因此“out”不会被截断,但会破坏链接过程,因此没有“out2”。有任何想法吗?

temp = subprocess.Popen(call, stdout=subprocess.PIPE)
#time.wait(1)
#subprocess.Popen.wait(temp)
temp2 =  subprocess.Popen(call2, stdin=temp.stdout, stdout=subprocess.PIPE)
out, err = temp.communicate()
out2, err2 = temp2.communicate()
4

2 回答 2

0

根据Python 文档, communicate() 可以接受要作为输入发送的流。如果您更改stdintemp2subprocess.PIPE放入outcommunicate(),则数据将正确传输。

#!/usr/bin/env python
import subprocess
import time

call = ["echo", "hello\nworld"]
call2 = ["grep", "w"]

temp = subprocess.Popen(call, stdout=subprocess.PIPE)

temp2 =  subprocess.Popen(call2, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = temp.communicate()
out2, err2 = temp2.communicate(out)

print("Out:  {0!r}, Err:  {1!r}".format(out, err))
# Out:  b'hello\nworld\n', Err:  None
print("Out2: {0!r}, Err2: {1!r}".format(out2, err2))
# Out2: b'world\n', Err2: None
于 2013-04-30T04:15:53.747 回答
0

文档中的“替换 shell 管道”部分之后:

temp = subprocess.Popen(call, stdout=subprocess.PIPE)
temp2 =  subprocess.Popen(call2, stdin=temp.stdout, stdout=subprocess.PIPE)
temp.stdout.close()
out2 = temp2.communicate()[0]
于 2013-05-01T00:25:30.003 回答