如何处理python中的套接字异常并继续执行脚本?

How to handle the socket exception in python and continue the script execution?

我正在尝试使用套接字从域列表中获取状态 returns。在这里,如果套接字由于任何情况而无法解析任何随机域,它会自行停止执行并且不会考虑从列表中进一步解析

def getDate_andTime():
  return 'time'

def get_HostName(domainName):
    value = socket.gethostbyname_ex(domainName)
    try:
        if not str(value[0]).startswith("[Errno") and str(value[0] !=''):
            return True, value[0],getDate_andTime()
        elif str(value[0]).startswith("[Errno"):
            print("Value is not available")
            return False, value[0], getDate_andTime()
    except socket.gaierror as e:
        print("Error log", socket.gaierror)
    return False,e, getDate_andTime()


#Invoking the method
listofdomain=['abc.com','bcd.com','ade.com']
for domain in listofdomain:
    condition, value, time= get_HostName(domain)

此处如果 'bcd.com' 未解决,脚本将停止而不考虑 'ade.com' 即使我已捕获异常。

谁能帮忙解决这个问题

您需要将 return 语句压入 except 块中。异常变量 e 的范围仅在 except 块内。

例如:

def get_HostName(domainName):
    try:
        value = socket.gethostbyname_ex(domainName)
        if not str(value[0]).startswith("[Errno") and str(value[0] !=''):
            return True, value[0],getDate_andTime()
        elif str(value[0]).startswith("[Errno"):
            print("Value is not available")
            return False, value[0], getDate_andTime()
    except socket.gaierror as e:
        print("Error log", socket.gaierror)
        return False,e, getDate_andTime()