为什么我在 file.close() 上收到 [Errno 9] 错误的文件描述符 - 错误处理

Why am I getting [Errno 9] Bad file descriptor on file.close() - error handling

我有以下代码:

版本 A

try:
    file = open(local_copy, "wt")
    n = file.write(str(soup))
    logging.debug(f'\t{local_copy} saved. {n} lines saved.')
except IOError as e:
    logging.error(traceback.print_exc())
finally:
    file.close()

版本 B

try:
    with open(local_copy, "wt") as file:
        n = file.write(str(soup))
    logging.debug(f'\t{local_copy} saved. {n} lines saved.')
except IOError as e:
    logging.error(traceback.print_exc())
finally:
    None

两者都因 [Errno 9] 错误的文件描述符而失败。它被堆栈上层的异常处理程序捕获。

现在,我将 True(布尔值)作为 local_copy 的值传递。我知道它会失败,但我的目标是正确处理错误。

我最终执行了以下操作,但我认为这不是最佳解决方案。我想知道为什么最初的 try...catch 块无法捕捉到它。有没有更好的不同方法来处理 IOErrors

if not isinstance(local_copy, str):
    logging.error(f"Cannot store localcopy of the file")
    logging.error(f'"local_copy" variable holds a value of an incorrect type: {type(local_copy)} (required str).')
else:
    try:
        file = open(local_copy, "wt")
        n = file.write(str(soup))
        logging.debug(f'\t{local_copy} saved. {n} lines saved.')
        # with open(local_copy, "wt") as file:
        #     n = file.write(str(soup))
        # 
        # logging.debug(f'\t{local_copy} saved. {n} lines saved.')
    except IOError as e:
        logging.error(traceback.print_exc())
    finally:
        file.close()
        #None

OSError 也没有捕获任何东西,以及 Exception。

独立示例:

import io

local_copy = True
soup = "Great soup"

try:
    file = open(local_copy, "wt")
    n = file.write(str(soup))
    print(f'\t{local_copy} saved. {n} lines saved.')
except OSError as e:
    print("we got the error")
finally:
    file.close()
print ("Done")

输出:

$ python3 test.py 
True saved. 10 lines saved.
Great soupTraceback (most recent call last):
 File "test.py", line 18, in <module>
    print ("Done")
OSError: [Errno 9] Bad file descriptor
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
OSError: [Errno 9] Bad file descriptor

为什么我的异常会被忽略? 另外,为什么汤的内容被发送到标准输出?

您的代码:

local_copy = True
....
file = open(local_copy, "wt")

从值 True 创建一个文件对象,它与整数 1 相同,表示标准输出的文件描述符,即默认情况下所有打印发出消息的通道。

(通常 open 与文件名一起使用 - 我猜你不打算写入标准输出。)

关闭该文件时,也就关闭了标准输出。该点之后的第一次打印将失败:

print("Done")

因为它无法打印到关闭输出。这是报告异常的原因。