在我下面的python脚本的snipet中,我认为temp2不等待temp完成运行,输出可能很大,但只是文本。这会从temp中截断结果('out'),它会停在mid line。来自temp的'out'工作正常,直到添加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()
答案 0 :(得分:0)
根据Python Docs communic()可以接受要作为输入发送的流。如果您将stdin
temp2
更改为subprocess.PIPE
并将out
置于communication()中,则会正确传输数据。
#!/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
答案 1 :(得分:0)
关注"Replacing shell pipeline" section from the docs:
temp = subprocess.Popen(call, stdout=subprocess.PIPE)
temp2 = subprocess.Popen(call2, stdin=temp.stdout, stdout=subprocess.PIPE)
temp.stdout.close()
out2 = temp2.communicate()[0]