0

code.InteractiveInterpreterをサブクラス化するとき、ドキュメントで期待するようにwrite()メソッドを実行できないようです。

import code

class PythonInterpreter(code.InteractiveInterpreter):
    def __init__(self, localVars):
        self.runResult = ''
        print 'init called'
        code.InteractiveInterpreter.__init__(self, localVars)

    def write(self, data):
        print 'write called'
        self.runResult = data

test = 'Hello'
interpreter = PythonInterpreter({'test':test})
interpreter.runcode('print test')
print 'Result:' + interpreter.runResult

期待される出力:

init called
write called
Result: Hello

実際の出力:

init called
Hello   <- shouldn't print
Result: 

何かご意見は?

4

1 に答える 1

3

write メソッドは、runco​​de に渡されるコードではまったく使用されません。これを機能させるには、stdout をリダイレクトする必要があります。たとえば、次のようになります。

import code

class PythonInterpreter(code.InteractiveInterpreter):
    def __init__(self, localVars):
        self.runResult = ''
        print 'init called'
        code.InteractiveInterpreter.__init__(self, localVars)

    def write(self, data):
        # since sys.stdout is probably redirected,
        # we can't use print
        sys.__stdout__.write('write called\n')
        self.runResult = data

    def runcode(cd):
        # redirecting stdout to our method write before calling code cd
        sys.stdout = self
        code.InteractiveInterpreter.runcode(self,cd)
        # redirecting back to normal stdout
        sys.stdout = sys.__stdout__
于 2013-03-09T13:29:02.700 に答える