是否存在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)

其他回答

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

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)

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

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

So

print 99

等价于:

import sys
sys.stdout.write(str(99) + '\n')
>>> 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而不是print。

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

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

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

你问,

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