1

如何在 Python 脚本中包装 bash shell 会话,以便 Python 可以将 stdout 和 stderr 存储到数据库,并偶尔写入 stdin?

我尝试使用带有类似 tee 的 Python 类的 subprocess 来重定向 IO,但它似乎使用 fileno 来完全绕过 Python。

外壳.py:

import os
import sys
from StringIO import StringIO
from subprocess import Popen, PIPE

class TeeFile(StringIO):
    def __init__(self, file, auto_flush=False):
        #super(TeeFile, self).__init__()
        StringIO.__init__(self)
        self.file = file
        self.auto_flush = auto_flush
        self.length = 0

    def write(self, s):
        print 'writing' # This is never called!!!
        self.length += len(s)
        self.file.write(s)
        #super(TeeFile, self).write(s)
        StringIO.write(self, s)
        if self.auto_flush:
            self.file.flush()

    def flush(self):
        self.file.flush()
        StringIO.flush(self)

    def fileno(self):
        return self.file.fileno()

cmd = ' '.join(sys.argv[1:])
stderr = TeeFile(sys.stderr, True)
stdout = TeeFile(sys.stdout, True)

p = Popen(cmd, shell=True, stdin=PIPE, stdout=stdout, stderr=stderr, close_fds=True)

例如 Runningpython shell.py ping google.com运行正确的命令并显示输出,但 Python 永远不会看到标准输出。

4

1 回答 1

1
#!/usr/bin/env python

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from twisted.internet import protocol
from twisted.internet import reactor
import re

class MyPP(protocol.ProcessProtocol):
    def __init__(self, verses):
        self.verses = verses
        self.data = ""
    def connectionMade(self):
        print "connectionMade!"
        for i in range(self.verses):
            self.transport.write("Aleph-null bottles of beer on the wall,\n" +
                                 "Aleph-null bottles of beer,\n" +
                                 "Take one down and pass it around,\n" +
                                 "Aleph-null bottles of beer on the wall.\n")
        self.transport.closeStdin() # tell them we're done
    def outReceived(self, data):
        print "outReceived! with %d bytes!" % len(data)
        self.data = self.data + data
    def errReceived(self, data):
        print "errReceived! with %d bytes!" % len(data)
    def inConnectionLost(self):
        print "inConnectionLost! stdin is closed! (we probably did it)"
    def outConnectionLost(self):
        print "outConnectionLost! The child closed their stdout!"
        # now is the time to examine what they wrote
        #print "I saw them write:", self.data
        (dummy, lines, words, chars, file) = re.split(r'\s+', self.data)
        print "I saw %s lines" % lines
    def errConnectionLost(self):
        print "errConnectionLost! The child closed their stderr."
    def processExited(self, reason):
        print "processExited, status %d" % (reason.value.exitCode,)
    def processEnded(self, reason):
        print "processEnded, status %d" % (reason.value.exitCode,)
        print "quitting"
        reactor.stop()

pp = MyPP(10)
reactor.spawnProcess(pp, "wc", ["wc"], {})
reactor.run()

这就是将命令 IO 作为协议处理的 Twisted 方式。顺便说一句,您也使用 StringIO 使您的脚本复杂化。而是检查 Popen.communicate() 方法。请注意,stdin/stdout 是文件描述符,需要并行读取,因为如果输出较长,它们的缓冲区将溢出。如果您想通过它流式传输大量数据,请使用 Twisted 方式,或者如果 Popen 方式触发单独的线程来读取标准输出,可能会逐行并立即将它们放入 DB。 关于处理协议的扭曲方法。

于 2012-07-03T21:11:17.427 回答