December 31st, 2012, 01:17 AM
Stdout issue in python
I am working on a script. Requirement is to divert all output to a file. I did this with below code-:
Now, after execution of the script i want to print one line to console that, please check the output in "output_file_name".
But this line also get printed inside the file instead of console. Can any one help?
December 31st, 2012, 01:38 AM
Back up the old sys.stdout into another variable before you make it write to a file:
old_stdout = sys.stdout
# Do stuff here
old_stdout.write("Something that goes to the screen\n")
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
December 31st, 2012, 02:15 AM
Originally Posted by Scorpions4ever
it is working. Thanks.
But can you explain the reason why we need to store the sys.stdout to some other variable ?
December 31st, 2012, 07:25 AM
You can also use sys.__stdout__ which is supposed to contain the "original" value of sys.stdout as of the start of the program.
December 31st, 2012, 08:26 AM
>>> a = 43
>>> a = 'a string'
>>> # how will you recover 43?
In recent python2 there's some print syntax that directs output to some file not stdout.
In python3 print is a function that accepts a keyword file destination.
Help on built-in function print in module builtins:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
Initially you might think as our group did that redirecting the print sink and input source are wonderful mechanisms for tests and whatnot. Later you'll realize that python has a wonderful StringIO class and that many functions are better off returning strings rather than directly printing them, and to separate opening files from using them. Instead of passing a file name argument pass open file-like objects.
[/code] are essential for python code and Makefiles!