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

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


当前回答

下面是一些基于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而不是print。

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

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

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

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

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

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

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()比print更可取的情况?

我发现在多线程情况下,stdout比print工作得更好。我使用队列(FIFO)来存储要打印的行,并且在打印行之前保持所有线程,直到打印队列为空。即便如此,使用print我有时会在调试I/O上丢失最后的\n(使用Wing Pro IDE)。

当我在字符串中使用带\n的std.out时,调试I/O格式正确且\n被准确地显示出来。