Friday 16 January 2015

redirect output in text file and terminal in python simultaneously

Hello Friends,

Today, I will tell u about how to print process output on terminal as well as in file parallel.

1) First Step to import necessary package on starting of python code.Copy below line and paste in your code.

import string, os, sys, stat ,re,subprocess

2) Copy below lines and paste in your code from where you want to print output on file.


sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
tee = subprocess.Popen(["tee", "terminal_log.txt"], stdin=subprocess.PIPE) os.dup2(tee.stdin.fileno(), sys.stdout.fileno())
os.dup2(tee.stdin.fileno(), sys.stderr.fileno())

It will generate "terminal_log.txt" file with output which is printed on terminal also.I hope it will use any many situation in your code.


Thanks all.

Come back soon with more interesting info.

No comments:

Post a Comment