繁体   English   中英

Python子进程.Popen通过管道进行通信

[英]Python subprocess.Popen communicate through a pipeline

我希望能够使用Popen.communicate并将stdout记录到文件中(除了从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)

与此相关的任何问题,看一下沟通的暗示,看起来都不错。 但是有更好的方法吗?

根据您对“ nicer”的定义,我会说,以下几点可能会更好,因为它避免了额外的发球过程:

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()提供了一个包装器,该包装器将stdout写入您选择的文件句柄,然后返回原始元组供您使用。 我省略了异常处理; 您可能应该补充一点,如果程序更关键。 另外,如果您希望创建多个Popen对象并希望它们都记录到同一文件中,则可能应该将logcommunicate()设置为线程安全的(每个文件句柄同步)。 您可以轻松扩展此解决方案,以将其写入stdout和stderr的单独文件。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM