我知道在运行下面的代码时,print(url, end='')
将首先打印一行。你知道吗
然后requests.get(url)
引发异常,从而触发traceback.print_exc()
。你知道吗
但是在我的测试中,traceback.print_exc()
比print(url, end='')
更早在屏幕上打印。你知道吗
为什么?你知道吗
另一方面,如果我将traceback.print_exc()
替换为print('error occurred')
,它将按照我的想法工作。你知道吗
似乎traceback.print_exc()
具有更高的优先级?你知道吗
import traceback
import requests
url = 'http://www.szwb.gov.cn/wap/jggk/gzdt/201809/t20180919_14099889.htm'
try:
print(url, end='')
response = requests.get(url)
# balabala
except Exception as e:
traceback.print_exc()
# print('error occurred.')
对于控制台的I/o,通常用python缓冲。发送错误报告的I/o对print函数调用具有更高的优先级。你知道吗
也就是说,
print(url, end='')
首先将其数据放入缓冲区。然后错误报告将其数据放入缓冲区。你知道吗当错误报告放入其数据时,打印函数的数据仍在缓冲区中,优先级较低。所以错误报告将数据放在前面,并显示在前面。你知道吗
print
将输出到STDOUT,traceback.print_exc()
将输出到STDERR。STDOUT是“缓冲”的,STDERR不是。从this article:当缓冲区被“刷新”时,它将被显示。通常,如果输出是一个终端,则在新行刷新缓冲区。你知道吗
在Python3中,可以使用
flush
kwarg强制执行此操作:实际上与:
或者,您可以删除
end
kwarg:请注意,这将在URL后面打印一个换行符。这可能是不可取的。你知道吗
相关问题 更多 >
编程相关推荐