[Python]print vs Sys.stdout.write

Source: Internet
Author: User

previously just seen in the project, did not pay much attention, just with the object to see the Python study manual, see this part of the study. Python version 2.7.xos Win7
Print is generally the time to execute the script, the information is printed directly to the standard output, that is, we usually say that the console print is a Python __builtin__ method, to see his 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 here we can see that print may be a bit more than we used to do. * Sep is used to make a separator between values, so when we print ' 2 ', ' a ', the actual middle is a space * end is wrapped by default, so print always prints a line of information * Print can also be output to a file, but we also 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 oh, the error, in fact, as long as the from __future__ import print_function can be used like Python3 parameters
In [6]: print (' A ', ' B ') a b in [7]: Print (' A ', ' B ', sep= '--')  #print multiple values without commas separated a--b in [8]: Print (' Nihao ');p rint (' Orangle ')   nihaoorangle in [9]: print (' Nihao ', end= ');p rint (' Orangle ')  #print no Line break Nihaoorangle

It's like print has a lot of gameplay. We directly write the value of print to the file object instead of the default Sys.stout test.
In [all]: F = open (' Test.txt ', ' W ') in []: Print (' haha.....csdn ', file=f) in []: LS test.txt the volume in drive D is not labeled. The serial number of the volume is the directory of 0002-fa2e D:\code\python 2015/01/20 Tuesday  10:37                 0 test.txt               1 files              0 bytes               0 directories 61,124,526,080 Free bytes in [+]: F.close ()
to the corresponding directory to see, test.txt content, sure enough ishaha.....csdn, but be sure to remember F.close (), if not closed, the content cannot be saved to the file.
Sys.stdout.writeThis method calls the Write method in the file object, writes the characters to the standard output, and looks similar to print.
  Def write (self, str): "" "    write (str)-None.  Write string str to file.        Note that due to buffering, flush () or close () is needed before the    file on disk reflects the data written. "" "    Return" "


What is the relationship between this method and print? We'll check to see if print is the rightSys.stdout.write's friendly package is also just seen from the Python learning Manual.
The difference between print can convert an object to STR and then put it in standard output, sys.stdout.write need to convert the object into an object first in the output
In [3]: Class A ():   ...:     def __str__ (self): ...:         return "a"   ...: in [5]: a = A () in [6]: Print AA in [9] : Import Sysin [ten]: Sys.stdout.write (a)-------------------------------------------------------------------------- -typeerror                                 Traceback (most recent) <ipython-input-10-0697f962911e> in <module> ()----> 1 Sys.stdout.write (a) typeerror:expected a character buffer object in [all]: Sys.stdout.write (str (a)) a
So I can't use it.Sys.stdout.write to replace print directly

How do you use the two together? Referencelearning a piece of code in Python
Import systemp = Sys.stdout #store Original stdout object for latersys.stdout = open (' Log.txt ', ' W ') #redirect all prints T o 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 inte Ractive Promptprint ("Back to normal") #this shows up in the interactive prompt

The Log.txt file saves the output as
Testing123another Line
we can put the debugging in the printed information stored in the file, so it is a way to chase and find errors
There is also the possibility of using sys.stdout.write to encapsulate Log writes in a multithreaded log

Reference article: 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 is from the "Orangleliu Notebook" blog, reproduced please be sure to keep this source http://blog.csdn.net/orangleliu/article/details/42915501

Author Orangleliu using Attribution-NonCommercial-sharing protocol in the same way

[Python]print vs Sys.stdout.write

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.