0 0 0 0

Turn from: python standard output sys. Stdout.

This article environment: python 2.7

Use print obj instead of print ( obj )

Some backgrounds.

Sys. Stdout and print.

When we print an object in python, it's actually called the sys. Stdout. Write ( obj + 'n ').

Print prints the contents you need to the console and then appends a line break.

Print calls the sys. Stdout write method.

The following two lines are actually equivalent:

print 'hello'

Sys. Stdin and raw_input.

As we use raw_input ( 'input promption:: '), we actually output the message, then capture the input

The following two groups are in fact equivalent:

hi=raw_input('hello? ')
print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the 'n' in input stream

Redirect from the co ole to a file

The original sys. Stdout point to the co ole.

If the reference to the object 's object is assigned to sys. Stdout, then print calls the file object 's write method.

f_handler=open('out.log', 'w')
print 'hello' 
# this hello can't be viewed on concole
# this hello is in file out.log

Remember, if you also want to print something on the console, it's better to save the original console object reference to the file and then restore the sys. Stdout.

# redirection start
#.. .
# redirection end
Redirect to co ole and file

What if we want to print the contents to the console on one side, on the other hand, the output to the file?

Leave the printed content in memory instead of a print to release the buffer, so how to put it in a string region.

print 'hello'

Ok, the above code isn't functioning properly

Traceback (most recent call last):
 File"", line xx, in <module>
 print 'hello'
AttributeError: 'str' object has no attribute 'write'

The error is clearly highlighted above, and it's noted that there's no write method when trying to call sys. Stdout. Write ( ).

In addition, the reason for attribute error I & tead of the function isn't found, I guess that python treats the object class pointer record as an attribute of the object class, except that the entry address of the function is retained.

Now that you've this, we must implement a write method for the redirected object:

import sys
class __redirection__:
 def __init__(self):
 def write(self, output_stream):
 def to_console(self):
 print self.buff
 def to_file(self, file_path):
 print self.buff
 def flush(self):
 def reset(self):
if __name__=="__main__":
 # redirection
 # get output stream
 print 'hello'
 print 'there'
 # redirect to console
 # redirect to file
 # flush buffer
 # reset

In the same, sys. Stderr, sys.stdin can be redirected to multiple addresses, for a thing to do.

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs