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

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


当前回答

我的问题是,是否存在sys.stdout.write()优于print的情况

如果您正在编写一个既可以写入文件又可以写入标准输出的命令行应用程序,那么它就很方便。你可以这样做:

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()

这确实意味着不能使用with open(outfile, 'w')作为out:模式,但有时这样做是值得的。

其他回答

其中一个区别如下,当试图将一个字节打印为其十六进制外观时。例如,我们知道十进制值255是十六进制的0xFF:

val = '{:02x}'.format(255)

sys.stdout.write(val) # Prints ff2
print(val)            # Prints ff
>>> 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

我的问题是是否有 在这些情况下 Sys.stdout.write()更可取 打印

有一天,在完成一个脚本的开发后,我把它上传到unix服务器上。我的所有调试消息都使用打印语句,这些语句不会出现在服务器日志中。

在这种情况下,您可能需要sys.stdout.write来代替。

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而不是print。

当您希望覆盖一行而不转到下一行时,例如在绘制进度条或状态消息时,您需要在以下内容上进行循环

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

由于print添加了换行符,您最好使用sys.stdout。