是否存在sys.stdout.write()比print更可取的情况?
(例子:更好的性能;更有意义的代码)
是否存在sys.stdout.write()比print更可取的情况?
(例子:更好的性能;更有意义的代码)
当前回答
>>> 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.write() 打印吗?
例如,我正在处理一个小函数,它在传递数字作为参数时以金字塔格式打印星星,尽管您可以使用end=""在单独的行中打印来完成这一点,但我使用sys.stdout.write与print配合使用来完成此工作。详细说明此标准输出。在同一行中写入打印,而as print总是在单独一行中打印其内容。
import sys
def printstars(count):
if count >= 1:
i = 1
while (i <= count):
x=0
while(x<i):
sys.stdout.write('*')
x = x+1
print('')
i=i+1
printstars(5)
>>> 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的情况
如果您正在编写一个既可以写入文件又可以写入标准输出的命令行应用程序,那么它就很方便。你可以这样做:
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:模式,但有时这样做是值得的。