Mar-22-2020, 05:25 PM
(This post was last modified: Mar-22-2020, 05:25 PM by deanhystad.)
I made quite a lot of headway. I have a way of entering python code in a GUI control that works much line code.InteractiveConsole and I redirect stdout and stderr so they appear in my GUI:
One idea I have is creating a redirect class that calls another function when it's write method gets called. I added an errorwrite method to my console class and create a redirect object to call that method. Then I redirect stderr to my redirect object instead of the console
Also, at what point is it polite to provide code snippets instead of enough code for a working example. My console.py file is 160 lines long and there isn't much fat to remove and still have it work.
import sys import code import PySide2.QtWidgets as QtWidgets import PySide2.QtCore as QtCore import PySide2.QtGui as QtGui from contextlib import redirect_stdout, redirect_stderr class Console(QtWidgets.QWidget): <snip> def write(self, line: str): self.writeoutput(line, self.outfmt) def writeoutput(self, line: str, fmt: QtGui.QTextCharFormat=None) -> None: if fmt is not None: self.outdisplay.setCurrentCharFormat(fmt) self.outdisplay.appendPlainText(line.rstrip()) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) console = Console() <snip> with redirect_stdout(console), redirect_stderr(console): console.show() sys.exit(app.exec_())The program creates a format for characters typed as input (black) and another for captured output (blue). I would like a third format (red) for captured stderr. How do I differentiate stdout from stderr?
One idea I have is creating a redirect class that calls another function when it's write method gets called. I added an errorwrite method to my console class and create a redirect object to call that method. Then I redirect stderr to my redirect object instead of the console
class Redirect(): def __init__(self, func): self.func = func def write(self, line:str): self.func(line) class Console(QtWidgets.QWidget): <snip> def errorwrite(self, line: str): self.writeoutput(line, self.errfmt) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) console = Console() redirect = Redirect(console.errorwrite) with redirect_stdout(console), redirect_stderr(redirect): console.show() sys.exit(app.exec_())This works, but is there a better way?
Also, at what point is it polite to provide code snippets instead of enough code for a working example. My console.py file is 160 lines long and there isn't much fat to remove and still have it work.