【问题标题】:Python, changing the write method of sys.stdoutPython,改变 sys.stdout 的 write 方法
【发布时间】:2015-01-27 10:12:17
【问题描述】:

我有这个代码:

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 方法?

【问题讨论】:

  • 您介意分享完整的日志吗?
  • 完成,发布错误
  • 你的代码的目的是什么?
  • 重定向输出到文件对象。我只更改了问题

标签: python stdout


【解决方案1】:

对于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__

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2013-01-18
    • 2013-01-01
    • 2023-02-04
    • 2016-10-31
    相关资源
    最近更新 更多