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
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
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:模式,但有时它是值得的。
例如,我正在编写一个小函数,该函数在传递数字作为参数时以金字塔格式打印星星,尽管您可以使用< em >结束= " " < / em >在单独的行中打印来完成此任务,但我使用< em > sys.stdout.write < / em >与< em > < / em >打印配合使用来实现此工作。要详细说明这一点,stdout.write打印在同一行中,而打印总是在单独的行中打印其内容。
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)
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)
>>> 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