【问题标题】:Python subprocess.Popen communicate through a pipelinePython subprocess.Popen 通过管道进行通信
【发布时间】:2010-08-11 08:38:25
【问题描述】:

我希望能够使用Popen.communicate 并将标准输出记录到文件中(除了从communicate() 返回。

这正是我想要的——但这真的是个好主意吗?

cat_task = subprocess.Popen(["cat"],  stdout=subprocess.PIPE, stdin=subprocess.PIPE)
tee_task = subprocess.Popen(["tee", "-a", "/tmp/logcmd"], stdin=cat_task.stdout, 
    stdout = subprocess.PIPE, close_fds=True)
cat_task.stdout = tee_task.stdout #since cat's stdout is consumed by tee, read from tee.
cat_task.communicate("hello there")
('hello there', None)

这方面的任何问题,看看通信的 impl 看起来不错。但是有更好的方法吗?

【问题讨论】:

    标签: python subprocess popen


    【解决方案1】:

    根据您对“更好”的定义,我会说以下内容可能更好,因为它避免了额外的 tee 流程:

    import subprocess
    
    def logcommunicate(self, s):
        std = self.oldcommunicate(s)
        self.logfilehandle.write(std[0])
        return std
    
    subprocess.Popen.oldcommunicate = subprocess.Popen.communicate
    subprocess.Popen.communicate = logcommunicate
    logfh = open("/tmp/communicate.log", "a")
    
    proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    proc.logfilehandle = logfh
    
    result = proc.communicate("hello there\n")
    print result
    

    简而言之,它为communicate() 提供了一个包装器,它将标准输出写入您选择的文件句柄,然后返回原始元组供您使用。我省略了异常处理;如果程序更关键,您可能应该添加。此外,如果您希望创建多个 Popen 对象并希望它们全部记录到同一个文件,您可能应该安排 logcommunicate() 是线程安全的(每个文件句柄同步)。您可以轻松扩展此解决方案,将其写入 stdout 和 stderr 的单独文件。

    请注意,如果您希望来回传递大量数据,那么 communicate() 可能不是最佳选择,因为它会缓冲内存中的所有内容。

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 2010-12-26
      • 2011-02-09
      相关资源
      最近更新 更多