【问题标题】:Python 3 - tkinter , ignore socket.herror and continuePython 3 - tkinter,忽略 socket.herror 并继续
【发布时间】:2016-07-04 15:16:45
【问题描述】:

我尝试通过我使用 Tkinter 制作的 GUI 使用套接字模块解析主机 这是代码的一部分,主要问题是我在解析路由器名称时收到的错误

for line in p.stdout:
            fiw = open("1.txt", '+a')
            line = str(line)
            if "Received = 1" in line:
                hostad = socket.gethostbyaddr(ip3 +str(i))
                if hostad:
                    try:
                        print(hostad)
                    except socket.herror:
                        print(hostad)
                fiw.write("Received reply from " + ip3 +str(i)+"\n")
                print("Received reply from " + ip3 +str(i)+"\n")
                print(socket.gethostbyaddr(ip3 +str(i)))

错误:

socket.herror: [Errno 11004] host not found

脚本不会进一步运行,我在这里使用了print,例如我也尝试过pass 试过了

except socket.herror as err:
              print(err)
              pass

也试过在这个方法中使用pass

【问题讨论】:

    标签: python windows python-3.x networking tkinter


    【解决方案1】:

    你已经尝试过......除了错误的事情, 而不是

    hostad = socket.gethostbyaddr(ip3 +str(i))
    if hostad:
        try:
            print(hostad)
        except socket.herror:
            print(hostad)
    

    应该是这样的

    try:
        hostad = socket.gethostbyaddr(ip3 +str(i))
        print(hostad)
    except socket.herror:
        pass # code to execute in case of error
    

    错误消息本身是指“反向 DNS 查找失败” 如Python Sockets: gethostbyaddr : Reverse DNS Lookup Failure中所述

    如果主机名在一行中形成

    hostad = socket.gethostbyaddr(ip3 +str(i))
    

    没有反向DNS记录,抛出异常。

    【讨论】:

    • 你知道获取设备版本/名称的其他解决方案吗,比如 nmap 呢?
    【解决方案2】:

    我认为你应该看看这个thread

    异常就像一个断点,它会破坏你的 for 循环..

    试试这样:

    for line in p.stdout:
       try:
            fiw = open("1.txt", '+a')
            line = str(line)
            if "Received = 1" in line:
                hostad = socket.gethostbyaddr(ip3 +str(i))
                if hostad:
                    try:
                        print(hostad)
                    except socket.herror:
                        print(hostad)
                fiw.write("Received reply from " + ip3 +str(i)+"\n")
                print("Received reply from " + ip3 +str(i)+"\n")
                print(socket.gethostbyaddr(ip3 +str(i)))
       except:
                pass
    

    【讨论】:

    • inner try ... except 毫无意义,print 永远不会抛出 socket.herror。外部try ... except 捕获所有异常,这通常是不好的做法。
    猜你喜欢
    • 2013-03-17
    • 2010-10-09
    • 2019-01-05
    • 2019-04-10
    • 2011-12-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多