是否有可能print sys.stdout.write()情况?
( 示例:更好的性能;更有意义的代码)
#1楼
以下是一些基于Mark Lutz 学习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
#2楼
我的问题是,是否存在sys.stdout.write()更适合print
如果您正在编写可以写入文件和stdout的命令行应用程序,那么它很方便。 你可以这样做:
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') as out: pattern,但有时它是值得的。
#3楼
在2.x中, print语句预处理您提供的内容,沿途将其转换为字符串,处理分隔符和换行符,并允许重定向到文件。 3.x将其变成一个函数,但它仍然具有相同的职责。
sys.stdout是一个类似于文件或文件的文件,它具有写入它的方法,这些方法沿着该行获取字符串或其他内容。
#4楼
print首先将对象转换为字符串(如果它不是字符串)。 如果它不是行的开头和结尾处的换行符,它也会在对象之前放置一个空格。
使用stdout ,您需要自己将对象转换为字符串(例如,通过调用“str”),并且没有换行符。
所以
print 99
相当于:
import sys
sys.stdout.write(str(99) + '\n')
#5楼
print只是一个瘦的包装器,可以对输入进行格式化(可修改,但默认情况下在结尾处有args和newline之间的空格)并调用给定对象的write函数。 默认情况下,此对象为sys.stdout ,但您可以使用“chevron”表单传递文件。 例如:
print >> open('file.txt', 'w'), 'Hello', 'World', 2+3
在Python 3.x中, print成为一个函数,但由于file参数,仍然可以传递sys.stdout以外的东西。
print('Hello', 'World', 2+3, file=open('file.txt', 'w'))
在Python 2.6+中, print仍然是一个声明,但它可以用作函数
from __future__ import print_function
更新:Bakuriu评论指出print函数和print语句之间存在细微差别(更常见的是函数和语句之间)。
如果在评估参数时出错:
print "something", 1/0, "other" #prints only something because 1/0 raise an Exception
print("something", 1/0, "other") #doesn't print anything. The function is not called