从Python Popen在Redis中存储stdout和stderr

时间:2016-05-13 04:36:18

标签: python redis

我想运行一个命令并将结果存储在Redis中。

虽然演示的命令是 ls / etc ,但在现实生活中,我想将它用于长时间运行的过程。

我已经写了一些演示代码来展示这个想法。

不幸的是,这个代码在运行时坚持使用fileno,并且不起作用,即使我模拟了一个。我怎么能做到这一点?

import subprocess

import redis

class RedisFile:

    def __init__(self, key):
        self.key = key
        self.redis = redis.StrictRedis()

        print("inited RedisFile with key:", key)

    def write(self, value):
        self.redis.append(self.key, value)


def main():
    out = RedisFile("out")
    error = RedisFile("error")

    proc = subprocess.Popen(["ls", "/etc"],
            stdout=out,
            stderr=error,
            bufsize=0
            )


main()

1 个答案:

答案 0 :(得分:0)

您应该使用自定义标准输出替换sys.stdout。
像这样的一个例子: from unittest.mock import patch with patch('sys.stdout', your_stdout),patch('sys.stderr', your_stderr): do_something