Python Forum
class that Redirects text from stdio to file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
class that Redirects text from stdio to file
#1
Hello,

Here's a Class to redirect stdio to a file.

I wrote a class that toggles stdio from within a script.
see the __name__ clause for usage
save the code as 'ToggleStdio.py'


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')
Usage:

import ToggleStdio

# instantiate the class
ts = ToggleStdio(filename='xxxx.txt')  

ts.toggle_stdout()   # toggles between screen and file may be called once at beginning of a block of code, and once at end

                               # Can be used for more than one block of code, but be aware, nesting may cause unpredictable results.

Larz60+


Messages In This Thread
class that Redirects text from stdio to file - by Larz60+ - Sep-29-2016, 10:44 AM

Forum Jump:

User Panel Messages

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