MyTetra Share
Делитесь знаниями!
The difference between sys.stdout.write and print?
Время создания: 16.07.2018 11:27
Текстовые метки: python stdout write print
Раздел: Python
Запись: Velonski/mytetra-database/master/base/153172246442207k23ig/text.html на raw.githubusercontent.com

Are there situations in which sys.stdout.write() is preferable to print?


(Examples: better performance; code that makes more sense)


python printing stdout

shareimprove this question

edited Nov 17 '17 at 16:55


martineau

60.6k785158

asked Jul 16 '10 at 9:53


Johanna Larsson

5,08132644

4

Which version of Python? 2.x or 3.x? – Mark Byers Jul 16 '10 at 9:54

Honestly I'd like to know for both, although I have no experience with Python 3. Updated the question. – Johanna Larsson Jul 16 '10 at 9:59

11

@S.Lott : asking for the basic differences between sys.stdout.write() and print (and/or why Python has both) is a perfectly reasonable question and does not need examples. OP did not say the command syntax was confusing. – smci Jan 20 '15 at 22:07

add a comment

8 Answers

active oldest votes

up vote

216

down vote

accepted

print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the "chevron" form. For example:


print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


In Python 3.x, print becomes a function, but it is still possible to pass something else than sys.stdout thanks to the fileargument.


print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

See https://docs.python.org/3/library/functions.html#print


In Python 2.6+, print is still a statement, but it can be used as a function with


from __future__ import print_function

Update: There is a little difference between the print function and the print statement (and more generally between a function and a statement) pointed by Bakuriu in comments.


In case of error when evaluating arguments:


print "something", 1/0, "other" #prints only something because 1/0 raise an Exception


print("something", 1/0, "other") #doesn't print anything. The func is not called

shareimprove this answer

edited Feb 13 '17 at 7:43

answered Jul 16 '10 at 10:06


luc

24.9k1598148

35

It's also worth noting that print also appends a newline to whatever you write which doesn't happen with sys.stdout.write. – Michael Mior Jul 16 '10 at 11:49

@Michael Mior: True, I've said that "it formats the inputs". Better answser would mention what kind of formatting. Thanks for clarification. – luc Jul 16 '10 at 13:35

1

Also sys.stdout.write is more universal if you ever need to write dual-version code (e.g. code that works simultaneously with Python 2.x as well as Python 3.x). – andreb Dec 16 '10 at 3:28

2

@MichaelMior You can suppress the newline that print appends with a trailing comma: print "this",; print "on the same line as this" – drevicko Jun 14 '14 at 15:13

1

sys.stdout.write() also buffers the input and might not flush the input to the fd immediately. in order to make sure that it behaves like the print function, you should add: sys.stdout.flush() – kerbelp Nov 16 '17 at 7:27

show 3 more comments

up vote

108

down vote

"print" first converts the object to a string (if it is not already a string). It will also put a space before the object if it is not the start of a line and a newline character at the end.


When using stdout, you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character.


So


print 99

is equivalent to:


import sys

sys.stdout.write(str(99) + '\n')

shareimprove this answer

edited Jul 16 '10 at 10:22

answered Jul 16 '10 at 10:03


dogbane

179k57303367

25

+1 for mentioning the newline character! This is the main difference between print and .write(), I'd say. – Eric Lebigot Jul 16 '10 at 14:19

8

NOTE: print can be made to omit the newline. In Python 2.x, put a comma at the end, and a space character will be output, but no newline. E.g. print 99, In Python 3, print(..., end='') will avoid adding newline (and also avoid adding space, unless you do end=' '. – ToolmakerSteve Dec 19 '13 at 2:36

21

@EOL How funny is that, that someone named EOL makes a comment about '\n'... It made me laugh. I have no life. Kill me. – Depado Jun 23 '15 at 14:14

2

that's NOT true, print operation behaves slightly different in signal handlers in python2.X, i.e. print can not be replaced with sys.stdout in example: stackoverflow.com/questions/10777610/… – ddzialak Oct 27 '15 at 13:13

add a comment

up vote

30

down vote

My question is whether or not there are situations in which sys.stdout.write() is preferable to print


After finishing developing a script the other day, I uploaded it to a unix server. All my debug messages used print statements, and these do not appear on a server log.


This is a case where you may need sys.stdout.write instead.


shareimprove this answer

edited Sep 29 '12 at 15:17


Zearin

7471127

answered Jul 16 '10 at 10:59


LiamSullivan

43335

3

huh? Are you sure this is a difference between print() and sys.stdout.write(), as opposed to the difference between stdout and stderr? For debugging, you should use the logging module, which prints messages to stderr. – ostrokach Jan 25 '16 at 3:05

Ya. Same is true with using nohup and redirecting to a .out file. – conner.xyz May 9 '16 at 15:36

use of sys.stdout.flush() would help. – suprit chaudhary Jun 2 at 1:57

add a comment

up vote

27

down vote

Here's some sample code based on the book Learning Python by Mark Lutz that addresses your question:


import sys

temp = sys.stdout # store original stdout object for later

sys.stdout = open('log.txt', 'w') # redirect all prints to this log file

print("testing123") # nothing appears at interactive prompt

print("another line") # again nothing appears. it's written to log file instead

sys.stdout.close() # ordinary file object

sys.stdout = temp # restore print commands to interactive prompt

print("back to normal") # this shows up in the interactive prompt

Opening log.txt in a text editor will reveal the following:


testing123

another line

shareimprove this answer

edited Jun 18 '16 at 5:54


KeyWeeUsr

5,05181752

answered Aug 29 '12 at 16:43


Will Townes

8551915

Is there any way so that I can print to screen as well as write to the file? – Devesh Saini May 12 '14 at 4:15

4

@DeveshSaini: Yes, just overwrite sys.stdout with a proxy class that has at least a write() and flush() function. I wrote an example snippet here. – ponycat May 21 '14 at 9:08

add a comment

up vote

8

down vote

My question is whether or not there are situations in which sys.stdout.write() is preferable to print


If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:


def myfunc(outfile=None):

if outfile is None:

out = sys.stdout

else:

out = open(outfile, 'w')

try:

# do some stuff

out.write(mytext + '\n')

# ...

finally:

if outfile is not None:

out.close()

It does mean you can't use the with open(outfile, 'w') as out: pattern, but sometimes it is worth it.


shareimprove this answer

edited Jul 7 '13 at 22:00

answered Jul 7 '13 at 20:40


Hamish Downer

9,379107376

add a comment

up vote

7

down vote

There's at least one situation in which you want sys.stdout instead of print.


When you want to overwrite a line without going to the next line, for instance while drawing a progress bar or a status message, you need to loop over something like


Note carriage return-> "\rMy Status Message: %s" % progress

And since print adds a newline, you are better off using sys.stdout.


shareimprove this answer

answered Aug 31 '16 at 15:24


Carlos

3,34553565

add a comment

up vote

3

down vote

In 2.x, the print statement preprocesses what you give it, turning it into strings along the way, handling separators and newlines, and allowing redirection to a file. 3.x turns it into a function, but it still has the same responsibilities.


sys.stdout is a file or file-like that has methods for writing to it which take strings or something along that line.


shareimprove this answer

answered Jul 16 '10 at 9:59


Ignacio Vazquez-Abrams

550k9310121118

add a comment

up vote

1

down vote

Are there situations in which sys.stdout.write() is preferable to print?


For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.


import sys


def printstars(count):


if count >= 1:

i = 1

while (i <= count):

x=0

while(x<i):

sys.stdout.write('*')

x = x+1

print('')

i=i+1


printstars(5)

Так же в этом разделе:
 
MyTetra Share v.0.65
Яндекс индекс цитирования