Python,改变了sys.stdout的write方法

时间:2015-01-27 10:12:18

标签: python stdout

我有这段代码:

class Sstdout(sys):
    def __init__(self,txtctrl):
        self.txtctrl = txtctrl
    def write(self,string):     
        self.txtctrl.write('hi '+string)

sys.stdout.write = Sstdout()    
os.dup2(some_odj.fileno(), sys.stdout.fileno())

Traceback (most recent call last):
    File "for_testing0.py", line 17, in <module>
        os.dup2(sock.fileno(), sys.stdout.fileno())
    AttributeError: 'Sstdout' object has no attribute 'fileno'

问题是如何正确更改sys.stdout.write方法?

1 个答案:

答案 0 :(得分:0)

对于python 3

import sys
import io

class MyStdout(io.TextIOWrapper):

    def __init__(self, msg, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.msg = msg

    def write(self, data):
        if data != "\n":
            super().write(self.msg)
        super().write(data)


sys.stdout = MyStdout("hi ", buffer=sys.stdout.buffer, line_buffering=True)

print("jim")

# original stdout
sys.__stdout__