【问题标题】:Why am I getting [Errno 9] Bad file descriptor on file.close() - error handling为什么我在 file.close() 上收到 [Errno 9] Bad file descriptor - 错误处理
【发布时间】:2020-10-14 10:23:27
【问题描述】:

我有以下代码:

版本 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 也没有捕获任何东西,以及异常。

独立示例:

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

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

【问题讨论】:

  • 当您尝试关闭已经关闭的文件时,可能会发生错误的文件描述符。但如上所述 - 请提供有关您的代码的更多详细信息。
  • @ThierryLathuille IOError 是自 Python 3.3 起 OSError 的别名
  • 我已经用独立的、可运行的例子更新了这个问题。

标签: python io ioerror


【解决方案1】:

您的代码:

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

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

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

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

print("Done")

因为它不能打印到关闭的输出。这就是报告异常的原因。

【讨论】:

  • 好的,这回答了问题的标准输出部分 - 谢谢!仍然,如何在 file.close() 上捕获第一个错误。为了清楚起见,我理解上面的代码失败了,我正在尝试改进错误处理。
  • @m0rt1m3r 但是close 不会失败;尝试一个只打开+关闭的小程序,没有打印。如果您还有其他问题,请准确描述代码首先应该做什么。
  • 你是对的:/我已经做了更多的调试,代码实际上在下面的打印语句中失败了(因为我关闭了标准输出)。我不知道描述符 1,谢谢。我将在我的代码中添加正确的类型检查并抛出 TypeError 异常。
猜你喜欢
  • 2021-12-05
  • 2013-06-16
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-24
  • 2016-04-15
  • 2020-02-25
  • 2020-12-04
相关资源
最近更新 更多