Creating a custom sys.stdout class?

What I'm trying to do is just get the output of some terminal commands to the wx.TextCtrl widget. I realized that the easiest way to achieve this is to create your own stdout class and overload the write function into the widget function.

class stdout:

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 like:

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

As a result, the following error occurs:

 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 for fixing this would be appreciated.

+6
python stdout
source share
3 answers

sys.stdout not a class , it is 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 create a simple object similar to this file! Duck seal is your friend ...

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

+11
source share

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

If all you have to do with stdout is to directly output some programs, don’t send all kinds of things there, don’t change sys.stdout , just create an instance of subprocess.Popen using your own file object ( createdTxtCtrl ) instead of sys.stdout .

0
source share

Won't sys.stdout = StdOut(createdTxtCtrl) create a circular dependency? Do not try to reassign sys.stdout to a class derived from sys.stdout .

-one
source share

All Articles