Creating a custom sys.stdout class?

。_饼干妹妹 提交于 2019-11-29 07:20:59
Alex Martelli

sys.stdout is not a class, it's an instance (of type file).

So, just do:

class StdOut(object):
    def __init__(self,txtctrl):
        self.txtctrl = txtctrl
    def write(self,string):
        self.txtctrl.write(string)

sys.stdout = StdOut(the_text_ctrl)

No need to inherit from file, just make a simple file-like object like this! Duck typing is your friend...

(Note that in Python, like most other OO languages but differently from Javascript, you only ever inherit from classes AKA types, never from instances of classes/types;-).

If all you need to implement is writing, there is no need to define a new class at all. Simply use createdTxtCtrl instead of StdOut(createdTxtCtrl), because the former already supports the operation you need.

If all you need to do with stdout is direct some programs' output there, not direct all kinds of stuff there, don't change sys.stdout, just instantiate the subprocess.Popen with your own file-like object (createdTxtCtrl) instead of sys.stdout.

Wouldn't sys.stdout = StdOut(createdTxtCtrl) create cyclical dependency? Try not reassigning sys.stdout to the class derived from sys.stdout.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!