Save standard to a varible : Standard Vars « Development « Python






Save standard to a varible


import sys
temp = sys.stdout                     # save for restoring
sys.stdout = open('log.txt', 'a')     # redirects prints to file

print x, y, x                         # print to file
 
sys.stdout = temp
print a, b, c                         # print to original stdout

log =  open('log.txt', 'a')     
print >> log, x, y, z                 # print to a file-like object
print a, b, c                         # print to original stdout


class FileFaker:
    def write(self, string):
    # do something with the string
    pass
    
    
import sys
sys.stdout = FileFaker()
print someObjects         # sends to the class write method

myobj = FileFaker()
print >> myobj, someObjects   # does not reset sys.stdout


           
       








Related examples in the same category