是否存在sys.stdout.write()比print更可取的情况?
(例子:更好的性能;更有意义的代码)
是否存在sys.stdout.write()比print更可取的情况?
(例子:更好的性能;更有意义的代码)
当前回答
至少在一种情况下,您需要sys。Stdout而不是print。
当您希望覆盖一行而不转到下一行时,例如在绘制进度条或状态消息时,您需要在以下内容上进行循环
Note carriage return-> "\rMy Status Message: %s" % progress
由于print添加了换行符,您最好使用sys.stdout。
其他回答
下面是一些基于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.write()更可取 打印
有一天,在完成一个脚本的开发后,我把它上传到unix服务器上。我的所有调试消息都使用打印语句,这些语句不会出现在服务器日志中。
在这种情况下,您可能需要sys.stdout.write来代替。
>>> 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()比print更可取的情况?
我发现在多线程情况下,stdout比print工作得更好。我使用队列(FIFO)来存储要打印的行,并且在打印行之前保持所有线程,直到打印队列为空。即便如此,使用print我有时会在调试I/O上丢失最后的\n(使用Wing Pro IDE)。
当我在字符串中使用带\n的std.out时,调试I/O格式正确且\n被准确地显示出来。
至少在一种情况下,您需要sys。Stdout而不是print。
当您希望覆盖一行而不转到下一行时,例如在绘制进度条或状态消息时,您需要在以下内容上进行循环
Note carriage return-> "\rMy Status Message: %s" % progress
由于print添加了换行符,您最好使用sys.stdout。