[Python] print vs sys. stdout. write, pythonsys. stdout

Source: Internet
Author: User

[Python] print vs sys. stdout. write, pythonsys. stdout
I just saw it in the project before. I didn't pay much attention to it. I just watched the python learning manual with the object. I saw this part and studied it. Python version 2.7.xos win7
Print is generally used to print the information directly to the standard output when executing the script, that is, the console print is a method in python _ builtin _ to see its definition.

def print(stream):  """ 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. """  pass
From this we can see that print may have more features than we commonly use * sep is used for delimiter between values, so when we print '2', 'A, the actual space is in the middle * end is a line break by default, so print always prints a line of information * In fact, print can also be output to the file, but we know that there is no parameter list behind print in python2.
In [2]: print ('a', 'b', sep='|')  File "<ipython-input-2-bcb798285c07>", line 1    print ('a', 'b', sep='|')                        ^SyntaxError: invalid syntax

Oh, an error is reported. In fact, as long as from _ future _ import print_function can use parameters like python3.
In [6]: print ('A', 'B') a B In [7]: print ('A', 'B', sep = '--') # print multiple values separated by commas (,) a -- B In [8]: print ('nihao'); print ('orange') nihaoorangle In [9]: print ('nihao', end = ''); print ('orange') # print nihaoorangle without wrapping

It seems that there are many ways to use print. We directly write the print value to the file object, instead of the default sys. stout test.
In [11]: f = open('test.txt ', 'w') In [12]: print ('haha ..... csdn ', file = f) In [15]: the volume In the ls test.txt drive D has no labels. The serial number of the volume is 0002-FA2E D: \ code \ python directory 2015/01/20 Tuesday 0 test.txt 1 file 0 bytes 0 directories 61,124,526,080 available bytes In [16]: f. close ()
The content of test.txt is haha... csdn, but remember f. close (). If it is not closed, the content cannot be saved to the file.
Sys. stdout. write this method calls the write method in the file object and writes the characters to the standard output, which looks similar to print.
  def write(self, str):    """ write(str) -> None.  Write string str to file.        Note that due to buffering, flush() or close() may be needed before    the file on disk reflects the data written. """    return ""


What is the relationship between this method and print? We can check whether print is a friendly encapsulation of sys. stdout. write, just as we can see from the python learning manual.
Difference print can convert an object into str and put it in the standard output. sys. stdout. write needs to convert the object into an object in the output
In [3]: class A():   ...:     def __str__(self):   ...:         return "A"   ...: In [5]: a = A()In [6]: print aA In [9]: import sysIn [10]: sys.stdout.write(a)---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-10-0697f962911e> in <module>()----> 1 sys.stdout.write(a) TypeError: expected a character buffer object In [11]: sys.stdout.write(str(a))A
Therefore, you cannot directly replace print with sys. stdout. write.

How can we use the two in combination? Reference a piece of code in Learning Python
import systemp = sys.stdout #store original stdout object for latersys.stdout = open('log.txt','w') #redirect all prints to this log fileprint("testing123") #nothing appears at interactive promptprint("another line") #again nothing appears. It is instead written to log filesys.stdout.close() #ordinary file objectsys.stdout = temp #restore print commands to interactive promptprint("back to normal") #this shows up in the interactive prompt

In the log.txt file, save the output result
testing123another line
We can save the information printed during debugging in the file, which is also a way to catch up with and find errors
In addition, sys. stdout. write may be used in multi-thread logs to encapsulate log writing.

Reference: http://woodpecker.org.cn/diveintopython/scripts_and_streams/stdin_stdout_stderr.html
Http://stackoverflow.com/questions/3263672/python-the-difference-between-sys-stdout-write-and-print

This article from the "orangleliu notebook" blog, reprint please be sure to keep this source http://blog.csdn.net/orangleliu/article/details/42915501

Author orangleliu adopts signature-non-commercial use-share protocol in the same way

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.