Created
February 9, 2012 04:32
-
-
Save dnene/1777313 to your computer and use it in GitHub Desktop.
Redirecting print - a) by reassigning to print b) creating a different variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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