PySimpleGUI / PySimpleGUI

Python GUIs for Humans! PySimpleGUI is the top-rated Python application development environment. Launched in 2018 and actively developed, maintained, and supported in 2024. Transforms tkinter, Qt, WxPython, and Remi into a simple, intuitive, and fun experience for both hobbyists and expert users.
https://www.PySimpleGUI.com
Other
13.33k stars 1.84k forks source link

[Enhancement] Option to route stdout and stderr to both the Output element and a text file #3405

Open jdevoldere opened 3 years ago

jdevoldere commented 3 years ago

Type of Issues (Enhancement, Error, Bug, Question)

Enhancement

Operating System

Windows 10

Python version

3.7

PySimpleGUI Port and Version

Ports = tkinter, Qt, WxPython, Web

PySimpleGUI Version: 4.29.0

tkinter version: 8.6.9

Your Experience Levels In Months or Years

2 years - Python programming experience 4 years - Programming experience overall no - Have used another Python GUI Framework (tkinter, Qt, etc) previously (yes/no is fine)?

You have completed these steps:

Description of Problem / Question / Details

For my use case I want to have stdout and stderr be displayed in the Output element but I also need it to be written to a text file.

Code To Duplicate

/

PySimpleGUI commented 3 years ago

I've started moving more towards the Multiline element for performing operations involving stdout/stderr. In the tkinter port you'll find parameters to indicate if stdout/stderr should be rerouted to that element. This was done so that the more advanced features of the Multiline can also be output to the same area of the window.

jdevoldere commented 3 years ago

Right now I've solved it like this:

class StdHandler:
    def __init__(self):
        self.file = open('log', 'a')

    def write(self, s):
        self.file.write(s)
        window['multiline'].print(s)

    def flush(self):
        return

sys.stdout = StdHandler()
sys.stderr = StdHandler()

Not sure if there's a better way of doing this and not sure if my rudimentary flush method would cause any issues...

@PySimpleGUI however for some reason an extra blank line gets printed to the multiline whilst this isn't the case in the text file; why is this?

PySimpleGUI commented 3 years ago

Glad you've got a working work-around you're happy with.

The extra linebreak in a Multiline does WAY back. There are a number of Issues that have discussed the behavior. The problem I ran into ultimately is that in order to remain backwards compatible, I needed to leave this extra \n on Multiline Elements as a ton of user programs have code that explicitly removes this character. If I were to remove it at this point, it would break a lot of code.

jdevoldere commented 3 years ago

An inelegant workaround:

window['multiline'].print(s)
cleaned_content = window['multiline'].Get().rstrip("\n") + "\n"
window['multiline'].Update(cleaned_content)