OSError: [Errno 9] python 3 中的文件描述符错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19624684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OSError: [Errno 9] Bad file descriptor in python 3
提问by yosh315
I'm a beginning/intermediate level programmer currently trying to write a simple web server in Python 3. However, whenever I run the module I get OSError: [Errno 9] Bad file descriptor. I've scoured the internet looking for answers, but I can't seem to figure this one out on my own. Here is the code and traceback:
我是一名初级/中级程序员,目前正在尝试用 Python 3 编写一个简单的 Web 服务器。但是,每当我运行该模块时,我都会收到 OSError: [Errno 9] Bad file descriptor。我已经在互联网上搜索了答案,但我似乎无法自己解决这个问题。这是代码和回溯:
#import socket module
from socket import *
serverSocket=socket(AF_INET,SOCK_STREAM)
#Prepare a server socket
serverSocket.bind(('IP address', 8000))
serverSocket.listen(1)
while True:
#Establish the connection
print('Ready to serve...')
(connectionSocket, addr) = serverSocket.accept()
print ('connected from',addr)
try:
message=connectionSocket.recv(1024)
filename=message.split()[1]
print (filename)
filename=message.split()[1]
f=open(filename[1:])
outputdata=f.read()
#Send one HTTP header line into socket
connectionSocket.send('HTTP/1.1 200 OK')
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError as err:
print ('IO error')
#Send response message for file not found
connectionSocket.send(b'file not found')
#Close client socket
connectionSocket.close()
serverSocket.close()
Traceback:
追溯:
Traceback (most recent call last):
File "/Users/BigRed/Desktop/SOS/webServer.py", line 17, in <module>
(connectionSocket, addr) = serverSocket.accept()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/socket.py", line 184, in accept
fd, addr = self._accept()
OSError: [Errno 9] Bad file descriptor
采纳答案by lalo
When there is a OIError, you're calling serverSocket.close()
. But when you re-enter in the while loop, you call serverSocket.accept()
without call serverSocket=socket(AF_INET,SOCK_STREAM)
, and this fails, because you've called the close()
当出现 OIError 时,您正在调用serverSocket.close()
. 但是当你重新进入 while 循环时,你serverSocket.accept()
没有调用 call serverSocket=socket(AF_INET,SOCK_STREAM)
,这失败了,因为你调用了close()
See this post
看到这个帖子
Hope help
希望帮助
PD:django developers don't use socket regularly. =)
PD:django 开发人员不经常使用套接字。=)