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 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+
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+