成功解決BUG:OSError: [Errno 9] Bad file descriptor
異常解讀
在 Python 代碼編寫(xiě)過(guò)程中,會(huì)出現(xiàn)如下錯(cuò)誤:
OSError: [Errno 9] Bad file descriptor
該錯(cuò)誤翻譯為中文是:
將一個(gè)無(wú)效的文件句柄(-1)傳遞給 os.close()
函數(shù),它試圖關(guān)閉該文件句柄。
由于該文件句柄無(wú)效,會(huì)引發(fā)TypeError,錯(cuò)誤消息將顯示為 "Invalid file handle: [WinError 6]"
(前提是在Windows操作系統(tǒng)上運(yùn)行該代碼)
實(shí)際編碼錯(cuò)誤如下圖所示。
解決思路
解決該BUG很容易,只需要檢查一下文件句柄是否是正確的即可了。
復(fù)查一下代碼,查看文件是否打開(kāi)。
錯(cuò)誤復(fù)現(xiàn)
可以在 Python 文件中輸入如下代碼,即可出現(xiàn)本文標(biāo)題所示錯(cuò)誤:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-658022.html
import os
file_handle = -1 # 無(wú)效的文件句柄
try:
os.close(file_handle) # 嘗試關(guān)閉無(wú)效的文件句柄
except TypeError as e:
print(f"TypeError: Invalid file handle: {e}")
錯(cuò)誤信息如下文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-658022.html
Traceback (most recent call last):
File "E:/pythonProject/QueueDemo.py", line 6, in <module>
os.close(file_handle) # 嘗試關(guān)閉無(wú)效的文件句柄
OSError: [Errno 9] Bad file descriptor
其他學(xué)習(xí)資料
- 《滾雪球?qū)WPython》專(zhuān)欄與實(shí)體書(shū):https://dream.blog.csdn.net/article/details/131268344
- 《爬蟲(chóng)100例》:https://blog.csdn.net/hihell/category_9280209.html
- 《Python爬蟲(chóng)120》:https://blog.csdn.net/hihell/category_11079529.html
到了這里,關(guān)于成功解決BUG:OSError: [Errno 9] Bad file descriptor(Python BUG)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!