是否存在sys.stdout.write()比print更可取的情况?
(例子:更好的性能;更有意义的代码)
是否存在sys.stdout.write()比print更可取的情况?
(例子:更好的性能;更有意义的代码)
当前回答
在某些情况下是否更适合使用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)
其他回答
其中一个区别如下,当试图将一个字节打印为其十六进制外观时。例如,我们知道十进制值255是十六进制的0xFF:
val = '{:02x}'.format(255)
sys.stdout.write(val) # Prints ff2
print(val) # Prints ff
在Python 3中,print和sys.stdout.write to指出的区别还在于在终端中执行时返回的值。在Python 3中,sys.stdout.write返回字符串的长度,而print只返回None。
因此,例如,在终端中以交互方式运行以下代码将打印出字符串后跟它的长度,因为当以交互方式运行时,长度将被返回并输出:
>>> sys.stdout.write(" hi ")
hi 4
下面是一些基于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 3中,使用sys.stdout进行打印是有正当理由的。写,但是这个原因也可以变成使用sys.stdout.write的原因。
这个原因是,现在print是python3中的一个函数,你可以重写它。所以你可以在一个简单的脚本中到处使用print,并决定这些print语句需要写入到stderr。你现在可以重新定义打印函数,你甚至可以通过使用内置模块改变打印函数全局。偏离了轨道。写可以指定文件是什么,但通过覆盖打印,还可以重新定义行分隔符或参数分隔符。
反之亦然。也许您完全确定写入到stdout,但也知道要将打印更改为其他内容,您可以决定使用sys.stdout。写,并使用打印错误日志或其他东西。
所以,你使用什么取决于你打算如何使用它。打印更灵活,但这可能是使用或不使用它的原因。我还是会选择比较灵活的款式,选择印花。另一个使用印刷版的原因是熟悉。现在更多的人知道你说的print是什么意思,而更少的人知道sys.stdout.write。