python子流程的第二步。Popen截断第一步的结果
在下面的python脚本片段中,我认为temp2不会等待temp完成运行,输出可能很大,但只是文本。这将截断temp的结果(“out”),并在中间停止。”在添加temp 2之前,“从temp输出”功能正常。我尝试添加time.wait()和subprocess.Popen.wait(temp)。这两者都允许temp运行到完成,这样“out”不会被截断,但会中断链接过程,从而没有“out2”。有什么想法吗python子流程的第二步。Popen截断第一步的结果,python,linux,python-2.7,subprocess,chaining,Python,Linux,Python 2.7,Subprocess,Chaining,在下面的python脚本片段中,我认为temp2不会等待temp完成运行,输出可能很大,但只是文本。这将截断temp的结果(“out”),并在中间停止。”在添加temp 2之前,“从temp输出”功能正常。我尝试添加time.wait()和subprocess.Popen.wait(temp)。这两者都允许temp运行到完成,这样“out”不会被截断,但会中断链接过程,从而没有“out2”。有什么想法吗 temp = subprocess.Popen(call, stdout=subproces
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()
根据communicate()可以接受作为输入发送的流。如果将temp2
的stdin
更改为subprocess.PIPE
并将out
放入communicate(),则数据将通过管道正确传输
#!/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
以下:
您是否需要脚本中来自
temp
的输出并将其输送到temp2
(类似于tee
实用程序),还是只想将其输送到temp2
?它将temp
的整个输出加载到内存中,但OP说输出可能很大。您可以使用子流程。如果您不介意将输出加载到内存中,请检查\u output()
。
temp = subprocess.Popen(call, stdout=subprocess.PIPE)
temp2 = subprocess.Popen(call2, stdin=temp.stdout, stdout=subprocess.PIPE)
temp.stdout.close()
out2 = temp2.communicate()[0]