为什么回溯打印比打印url早?

2024-09-27 00:12:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在运行下面的代码时,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.')

Tags: 代码importhttpurlget屏幕wwwerror
2条回答

对于控制台的I/o,通常用python缓冲。发送错误报告的I/o对print函数调用具有更高的优先级。你知道吗

也就是说, print(url, end='')首先将其数据放入缓冲区。然后错误报告将其数据放入缓冲区。你知道吗

当错误报告放入其数据时,打印函数的数据仍在缓冲区中,优先级较低。所以错误报告将数据放在前面,并显示在前面。你知道吗

print将输出到STDOUT,traceback.print_exc()将输出到STDERR。STDOUT是“缓冲”的,STDERR不是。从this article

By default, I/O in programs is buffered which means the IO is not served immediately byte by byte rather are served from a temporary storage to the requesting program... By buffering, the whole block is read into the buffer at once then the individual bytes are delivered to you from the (fast in-memory) buffer area.

当缓冲区被“刷新”时,它将被显示。通常,如果输出是一个终端,则在新行刷新缓冲区。你知道吗

在Python3中,可以使用flushkwarg强制执行此操作:

print(url, end='', flush=True)

实际上与:

import sys

# ...

print(url, end='')
sys.stdout.flush()

或者,您可以删除endkwarg:

print(url)

请注意,这将在URL后面打印一个换行符。这可能是不可取的。你知道吗

相关问题 更多 >

    热门问题