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