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

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


当前回答

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

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)

其他回答

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

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

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

在Python 2中。在X中,print语句对你给它的内容进行预处理,将其转换为字符串,处理分隔符和换行符,并允许重定向到文件。Python 3。X将其转换为一个函数,但它仍然具有相同的职责。

sys。Stdout是一个文件或类似文件的类,它有一些方法用于写入它,这些方法接受字符串或沿着这一行的东西。

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

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

So

print 99

等价于:

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

我的问题是,是否存在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和print的区别是什么?`

我所知道的解释它的最好方法是向您展示如何使用sys.stdout来编写print

下面我提供了三种不同的方法来实现python的print函数:

实现1

import sys

def print(*args, sep=" ", file=sys.stdout, end="\n") -> None:
    # implementation One
    file.write(sep.join(str(arg) for arg in args))
    file.write(end)

实现2

def print(*args, sep=" ", file=sys.stdout, end="\n") -> None:
    # Implementation 2    
    file.write(str(args[0]))
    for arg in args[1:]:
        file.write(sep)
        file.write(str(arg))
    file.write(end)
    return

实现3

def print(*args, sep=" ", file=sys.stdout, end="\n") -> None:
    # implementation 3 
    it = iter(args)
    arg = next(it)
    file.write(str(arg))
    try:
        while True:
            arg = next(it)
            file.write(sep)
            file.write(str(arg))
    except StopIteration:
        pass
    file.write(end)
    return None