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

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


当前回答

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

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

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

其他回答

在Python 2中,如果你需要传递一个函数,那么你可以将os.sys.stdout.write赋值给一个变量。你不能这样做(在REPL)打印。

>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>>

这和预期的一样。

>>> cmd=print
  File "<stdin>", line 1
    cmd=print
            ^
SyntaxError: invalid syntax

这是行不通的。印刷是一种神奇的功能。

当动态打印有用时,例如,在一个较长的过程中提供信息:

import time, sys
Iterations = 555
for k in range(Iterations+1):

    # Some code to execute here ...

    percentage = k / Iterations
    time_msg = "\rRunning Progress at {0:.2%} ".format(percentage)
    sys.stdout.write(time_msg)
    sys.stdout.flush()
    time.sleep(0.01)

我的问题是,是否存在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:模式,但有时这样做是值得的。

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

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

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

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

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

sys.stdout.write(val) # Prints ff2
print(val)            # Prints ff