Python Socket连接错误/异常处理?

0 投票
1 回答
2380 浏览
提问于 2025-04-18 09:18

我有一个循环,运行得很好,但在某些主机上会出现连接错误。可惜的是,这些错误会导致脚本崩溃,而不是跳过这些问题。我知道要处理这个问题,最好的办法是把出问题的那行代码(serveroutput = tn.read_until(b'STARTTLS'))放在一个try: except块里。我可以这样做,但我不太确定怎么捕获错误并让它继续执行。如果我加一个break,它会直接中断循环,导致脚本提前停止。我该怎么继续遍历j呢?我听说可以用'continue'来继续循环,但我是不是捕获了正确的异常呢?

我的代码:

def getServers():
    fp = open("mailserverdata.csv", "r")
    pt = from_csv(fp)
    fp.close()
    domains = txt_domains.get(1.0, 'end').splitlines()
    symbols = txt_symbols.get(1.0, 'end').splitlines()
    for x in range(len(domains)):
        #Start Get MX Record
        answers = dns.resolver.query(str(domains[x]), 'MX')
        #End Get MX Record
        #Start Get Employees
        if symbols[x]!='':
            xml = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.stocks%20where%20symbol%3D%22'+symbols[x]+'%22&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
            dom = parse(xml)
            numemployees = dom.getElementsByTagName('FullTimeEmployees')
            if len(numemployees)!=0:
                numemployees = numemployees[0].firstChild.nodeValue
        else:
            numemployees = 0
        #End Get Employees
        j=0
        tlsbool = 'N'
        verified = 'N'
        for rdata in answers:
            #Start Trim Domains
            output = str(rdata.exchange)
            output = output[:len(output)-1]
            print(output)
            #End Trim Domains
            #Start Telnet
            tn = telnetlib.Telnet(output,25)
            tn.write(b'ehlo a.com\r\n')
            serveroutput = tn.read_until(b'STARTTLS')
            checkvar = "STARTTLS"
            for checkvar in serveroutput:
                tlsbool = 'Y'
                break
            #End Telnet
            #Start verification
            if output.find(domains[x])>-1:
                verified = 'Y'
            #End verification
            if j==0:
                pt.add_row([domains[x],output,tlsbool,numemployees,verified])
            else:
                pt.add_row(['',output,tlsbool,'',verified])
            j = j + 1
    txt_tableout.delete(1.0, 'end')
    txt_tableout.insert('end',pt)
    root.ptglobal = pt

尝试捕获代码:

try:
    serveroutput = tn.read_until(b'STARTTLS')
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

完整的堆栈错误:

Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "C:\Users\kylec\Desktop\Data Motion\Mail Server Finder\mailserverfinder.py", line 58, in getServers
    serveroutput = tn.read_until(b'STARTTLS')
  File "C:\Python34\lib\telnetlib.py", line 317, in read_until
    self.fill_rawq()
  File "C:\Python34\lib\telnetlib.py", line 526, in fill_rawq
    buf = self.sock.recv(50)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

更新:

我尝试了以下代码,但收到了一个错误。

代码: try: serveroutput = tn.read_until(b'STARTTLS') except tn.ConnectionsResetError: continue

错误:

AttributeError: 'Telnet' object has no attribute 'ConnectionsResetError'

1 个回答

1

最后对我有效的是对@user3570335建议的一个修改。

try:
    serveroutput = tn.read_until(b'STARTTLS')
except Exception as e:
    tlsbool = '?'

撰写回答