本文介绍了创建自定义 sys.stdout 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的只是将一些终端命令的输出打印到 wx.TextCtrl 小部件.我认为最简单的方法是创建一个自定义标准输出类并将写入函数重载到小部件的函数.

What I'm trying to do is simply have the output of some terminal commands print out to a wx.TextCtrl widget. I figured the easiest way to accomplish this is to create a custom stdout class and overload the write function to that of the widget.

标准输出类:

class StdOut(sys.stdout):
    def __init__(self,txtctrl):
        sys.stdout.__init__(self)
        self.txtctrl = txtctrl

    def write(self,string):
        self.txtctrl.write(string)

然后我会做一些事情,例如:

And then I would do something such as:

sys.stdout = StdOut(createdTxtCtrl)
subprocess.Popen('echo "Hello World!"',stdout=sys.stdout,shell=True)

结果是以下错误:

Traceback (most recent call last):
File "mainwindow.py", line 12, in <module>
from systemconsole import SystemConsole
File "systemconsole.py", line 4, in <module>
class StdOut(sys.stdout):
TypeError: Error when calling the metaclass bases
file() argument 2 must be string, not tuple

任何解决此问题的想法将不胜感激.

Any ideas to fix this would be appreciated.

推荐答案

sys.stdout不是一个class,它是一个instance(file 类型).

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

所以,就这样做:

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

sys.stdout = StdOut(the_text_ctrl)

无需从file继承,只需像这样制作一个简单的类文件对象即可!鸭子打字是你的朋友...

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

(请注意,在 Python 中,与大多数其他面向对象语言一样,但与 Javascript 不同的是,您只能从类 AKA 类型继承,从不从类/类型的实例;-).

(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;-).

这篇关于创建自定义 sys.stdout 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:41