1

Pythonがstdoutとstderrをデータベースに保存し、場合によってはstdinに書き込むことができるように、bashシェルセッションをPythonスクリプトでどのようにラップしますか?

ティーのようなPythonクラスでサブプロセスを使用してIOをリダイレクトしようとしましたが、filenoを使用してPythonを完全にバイパスしているようです。

shell.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はstdoutを認識しません。

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をプロトコルとして処理するツイスト方式です。ところで、StringIOを使用するとスクリプトが複雑になります。むしろ、Popen.communicate()メソッドを確認してください。stdin / stdoutはファイル記述子であり、出力が長くなるとバッファがオーバーフローするため、並列に読み取る必要があることに注意してください。これを介して巨大なデータをストリーミングしたい場合は、むしろそのツイスト方法を使用します。または、Popenの方法でstdoutを読み取るための別のスレッドを起動する場合は、行ごとにそれらをDBにすぐに配置します。 プロセスプロトコルのツイストハウツー。

于 2012-07-03T21:11:17.427 に答える