0

I wrote a program to perform measurements and currently I launch it via the Spyder IDE. The program is written in Python 3.6.3. The GUI was made using PyQt5 and it should be the main focus of the user, but I also print() many informations in Spyder's console.

In preparation for switching to an .exe instead of a .py, since there will be no console anymore, I would like to add a LineEdit to my interface where all the printing would occur. Ideally it would display both my print()s and the various error messages generated during execution. How do I redirect those prints to a LineEdit?

Most of the information I found during my research was about making a LineEdit some kind of Windows cmd equivalent but examples were overkill compared to what I'm trying to do. Thanks in advance.

Guimoute
  • 4,407
  • 3
  • 12
  • 28

1 Answers1

0

A quick and dirty method is to just redefine the builtin print function.

from PyQt5 import QtWidgets

IS_EXE = True  # There is probably a way to detect this at runtime

class Window(QtWidgets.QPlainTextEdit):

    def __init__(self):
        super(Window, self).__init__()
        self.setReadOnly(True)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    win = Window()
    win.show()

    # Replace the builtin print function
    if IS_EXE:
        print = win.appendPlainText

    # Print some stuff
    print('foo')
    print('bar')

    app.exec_()
user3419537
  • 4,740
  • 2
  • 24
  • 42
  • Thanks, that sounds good enough for replacing **my** prints which is nice already. I wonder if there is also a way to grab the various error prints. – Guimoute Mar 29 '18 at 11:27
  • 1
    If you want everything from the console (sorry, missed the bit where you mentioned error messages) you can look into [redirecting stdout](https://www.blog.pythonlibrary.org/2016/06/16/python-101-redirecting-stdout/). The same can be done with stderr – user3419537 Mar 29 '18 at 11:33
  • Exactly what I was looking for. Thank you! – Guimoute Mar 29 '18 at 11:53