是否存在sys.stdout.write()比print更可取的情况?

(例子:更好的性能;更有意义的代码)


当前回答

在Python 3中,print和sys.stdout.write to指出的区别还在于在终端中执行时返回的值。在Python 3中,sys.stdout.write返回字符串的长度,而print只返回None。

因此,例如,在终端中以交互方式运行以下代码将打印出字符串后跟它的长度,因为当以交互方式运行时,长度将被返回并输出:

>>> sys.stdout.write(" hi ")
 hi 4

其他回答

Print首先将对象转换为字符串(如果它还不是字符串)。如果对象不是行首,它也会在对象前加一个空格,在对象末尾加一个换行符。

当使用stdout时,你需要自己将对象转换为字符串(例如,通过调用"str"),并且没有换行符。

So

print 99

等价于:

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

Print只是一个精简的包装器,它格式化输入(可修改,但默认在args和换行符之间有空格),并调用给定对象的write函数。缺省情况下,该节点为sys。Stdout,但您可以使用“雪佛龙”形式传递文件。例如:

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

见:https://docs.python.org/2/reference/simple_stmts.html?highlight=print print语句


在Python 3中。X, print变成了一个函数,但是仍然可以传递除了sys。Stdout感谢文件文档。

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

看到https://docs.python.org/3/library/functions.html打印


在Python 2.6+中,print仍然是一个语句,但它可以用作with的函数

from __future__ import print_function

更新:Bakuriu评论指出,print函数和print语句之间(更一般地说,是函数和语句之间)有一个很小的区别。

如果计算参数时出现错误:

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

print("something", 1/0, "other") #doesn't print anything. The function is not called
>>> sys.stdout.write(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1

观察上面的例子:

Sys.stdout.write不会写入非字符串对象,但print会 Sys.stdout.write最后不会添加新的行符号,但print会

如果我们深潜,

sys。Stdout是一个文件对象,可用于print()的输出

如果未指定print()的文件参数,则sys。将使用Stdout

下面是一些基于Mark Lutz的《Learning Python》一书的示例代码,它可以解决你的问题:

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

在文本编辑器中打开log.txt将显示以下内容:

testing123
another line

在某些情况下是否更适合使用sys.stdout.write() 打印吗?

例如,我正在处理一个小函数,它在传递数字作为参数时以金字塔格式打印星星,尽管您可以使用end=""在单独的行中打印来完成这一点,但我使用sys.stdout.write与print配合使用来完成此工作。详细说明此标准输出。在同一行中写入打印,而as print总是在单独一行中打印其内容。

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)