【问题标题】:Output from subprocess not saved子进程的输出未保存
【发布时间】:2014-05-21 03:02:11
【问题描述】:

当我在带有标准输入的 Popen 中使用标准输出时,我的进程无法运行。

def program():
    p = subprocess.Popen(link, shell=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
    out = p.communicate(longquery)
    print out

当我运行它时,我的输出是 (None, None) 尽管我确实有一个输出显示在控制台上。为什么会发生这种情况?如何保存输出的输出?

【问题讨论】:

    标签: python command-line subprocess


    【解决方案1】:

    您需要根据the manual 管道输出数据:

    “要在结果元组中获取 None 以外的任何内容,您还需要提供 stdout=PIPE 和/或 stderr=PIPE。”

    def program():
        p = subprocess.Popen(link, shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        out = p.communicate(longquery)
        print out
    

    【讨论】:

    • 您好,谢谢,但由于某种原因,当我输入标准输出时,程序似乎根本没有运行。
    • @user3651858:“似乎根本没有运行。” 没有提供信息。 p.communicate() 调用后的 p.returncode 是什么? out 的价值是什么?如果将link 替换为"echo abc" 会发生什么?如果 stdout=PIPE, stderr=STDOUT 在您的情况下重定向合并的输出,您可能应该问一个不同的问题。
    【解决方案2】:

    您还需要设置stdout=PIPE

    将您的代码更改为:

    from subprocess import Popen, PIPE, STDOUT
    
    
    def program():
        p = Popen(link, shell=True, stdin=PIPE, stderr=STDOUT, stdout=PIPE)
        out = p.communicate(longquery)
        print out
    

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多