2013-03-30 118 views
7

问题Python的线程未处理的异常

  1. 什么是异常的原因是什么?

  2. client是否导致任何错误?

  3. 如果有可能,请说明其他错误。

背景

我创建一个Python GUI插槽服务器。当客户端连接到我的服务器时,GUI窗口将打开(我仍在处理此问题)。但是,当客户端不会连接,我得到一个错误:

Unhandled exception in thread started by <function clientthread at 0x10246c230> 

由于实际的脚本是相当长的,我有provided a pastebin link.

这里是线程的代码。 s是我的socket对象的名称。

def clientthread(s): 

    #Sending message to connected client 
    #This only takes strings (words 
    s.send("Welcome to the server. Type something and hit enter\n") 

    #loop so that function does not terminate and the thread does not end 
    while True: 

     #Receiving from client 
     data = s.recv(1024) 
     if not data: 
      break 
     s.sendall(data) 
     print data 
    s.close() 

回溯

感谢您的建议Morten。这是回溯。

Socket Created 
Socket Bind Complete 
Socket now listening 
Connected 
Traceback (most recent call last): 
    File "/Users/BigKids/Desktop/Coding/Python 2/Sockets/Function/Server GUI Alpha Function.py", line 80, in clientthread 
    s.send("Welcome to the server. Type something and hit enter\n") 
    File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 170, in _dummy 
    raise error(EBADF, 'Bad file descriptor') 
error: [Errno 9] Bad file descriptor 

就个人而言,我相信很多错误是由于GUI。

谢谢!

+0

你的代码对我来说很好。什么导致异常? – Igonato

+0

@Igonato可能是客户断开连接,你不觉得吗?这通常会引发例外IIRC –

+0

@MortenJensen我添加了我的客户端。我会在15分钟内回来查看 - 我必须去和erg :) – xxmbabanexx

回答

2

其一,你可以捕获该异常,打印出来,看看它是什么:)

用一个try /周围以外的所有条款和任何异常发生时打印做到这一点,例如。

def clientthread(s): 
    try: 
     #Sending message to connected client 
     #This only takes strings (words 
     s.send("Welcome to the server. Type something and hit enter\n") 

     #loop so that function does not terminate and the thread does not end 
     while True: 

      #Receiving from client 
      data = s.recv(1024) 
      if not data: 
       break 
      s.sendall(data) 
      print data 
     s.close() 
    except Exception: 
     import traceback 
     print traceback.format_exc() 

我猜这是客户端断开的原因。这会导致一个异常,你应该适当地处理它。如果客户可以通过多种方式断开连接。通过超时告知您,在尝试发送内容等时断开连接。 所有这些情况都是可信的异常情况,您应该测试它们并处理它们。希望这会帮助你继续前进,如果没有,请评论:)