【问题标题】:Python. Second step of subprocess.Popen truncates results of firstPython。 subprocess.Popen 截断第一个结果的第二步
【发布时间】:2013-04-11 03:46:07
【问题描述】:

在下面我的 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()

【问题讨论】:

  • 您是否需要脚本中temp 的输出并将其通过管道传输到temp2(类似于tee 实用程序),还是只想将其通过管道传输到temp2

标签: python linux python-2.7 subprocess chaining


【解决方案1】:

关注"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]

【讨论】:

    【解决方案2】:

    根据Python Docscommunicate() 可以接受要作为输入发送的流。如果将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 加载到内存中,但 OP 说输出可能很大。如果您不介意将输出加载到内存中,可以使用 subprocess.check_output()
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多