Skip to content

Instantly share code, notes, and snippets.

@chengui
Created September 26, 2013 10:20
Show Gist options
  • Save chengui/6712300 to your computer and use it in GitHub Desktop.
Save chengui/6712300 to your computer and use it in GitHub Desktop.
how to catch external output to logger
log_file = open('example.log', 'a')
logging.basicConfig(stream=log_file, level=logging.DEBUG)
logging.debug("Test")
sys.stdout = log_file
sys.stderr = log_file
stdout_fd = os.dup(1)
stderr_fd = os.dup(2)
os.dup2(log_file.fileno(), 1)
os.dup2(log_file.fileno(), 2)
os.system("echo foo")
os.dup2(stdout_fd, 1)
os.dup2(stderr_fd, 2)
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment