Python Forum
How to send output to stout?
Thread Rating:
  • 2 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to send output to stout?
#5
Hello,

I wrote a class that toggles stdio from within a script.
Be aware that it

see the __name__ clause for usage
save the following as 'ToggleStdio.py'


# add
import sys

class ToggleStdio:
    def __init__(self, filename=None):
        self.savestdout = None
        self.stdio_redirected = False
        if filename:
            self.savefile = filename

    def toggle_stdout(self):
        if self.stdio_redirected:
            sys.stdout = self.savestdout
            self.savestdout = None
            self.stdio_redirected = False
        else:
            self.savestdout = sys.stdout
            sys.stdout = open(self.savefile, 'w')
            self.stdio_redirected = True

if __name__ == '__main__':
    ts = ToggleStdio('mystdio.txt')
    ts.toggle_stdout()
    print('This should go to file')
    ts.toggle_stdout()
    print('This should go to screen')
    ts.toggle_stdout()
    print('added to file')
    print('more added to file')
    ts.toggle_stdout()
    print('more on screen')
To use from your class, import ToggleStdio
then use as in __name__

Larz60+
Reply


Messages In This Thread
How to send output to stout? - by natv - Sep-28-2016, 11:31 AM
RE: How to send output to stout? - by Crimson King - Sep-28-2016, 01:01 PM
RE: How to send output to stout? - by natv - Sep-28-2016, 01:59 PM
RE: How to send output to stout? - by sparkz_alot - Sep-28-2016, 01:05 PM
RE: How to send output to stout? - by Larz60+ - Sep-28-2016, 06:48 PM
RE: How to send output to stout? - by micseydel - Sep-28-2016, 06:53 PM
RE: How to send output to stout? - by Larz60+ - Sep-29-2016, 10:32 AM
RE: How to send output to stout? - by natv - Sep-29-2016, 01:48 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Send The output of Gyroscope sensor to node red jenkins43 1 2,145 Feb-07-2019, 11:00 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020