Skip to content

Instantly share code, notes, and snippets.

@dnene
Created February 9, 2012 04:32
Show Gist options
  • Save dnene/1777313 to your computer and use it in GitHub Desktop.
Save dnene/1777313 to your computer and use it in GitHub Desktop.
Redirecting print - a) by reassigning to print b) creating a different variable
from functools import partial
mode = "debug"
def get_logger(stream = None) :
if stream is None :
return __builtins__.print
else :
return partial(__builtins__.print,file=stream)
def main() :
redirect = open("bar.txt","w")
log = get_logger()
log("Hello")
# Could create a log2 below instead
# Could also use separate loggers for policy
# driven redirection (as in normal loggers)
log = get_logger(redirect)
log("World!")
redirect.close()
if __name__ == "__main__" :
main()
from functools import partial
def main():
global print
print("Hello")
redirect = open("foo.txt","w")
print = partial(__builtins__.print,file=redirect)
print("World!")
redirect.close()
if __name__ == "__main__" :
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment