首页 > 解决方案 > 如何使用 PythonPing 处理错误异常?

问题描述

我正在尝试 ping 计算机列表,但在最后一个计算机名称上不断收到套接字错误,该计算机名称不是有效的计算机。我该如何处理这个错误?

from pythonping import ping
import socket

list = ["usadandc1", "usadandc2", "usadandc3", "alsdkfasd"]

for host in list:
    result = ping(host, count=1)
    if result.success():
        print(host ,'online')
    else:
        print(host, 'Offline')

这是输出:

usadandc1 online
usadandc2 online
usadandc3 online
Traceback (most recent call last):
  File "C:\Temp\PythonPing.py", line 7, in <module>
    result = ping(host, count=1)
  File "C:\Users\usa\AppData\Roaming\Python\Python37\site-packages\pythonping\__init__.py", line 52, in ping
    comm = executor.Communicator(target, provider, timeout, socket_options=options, verbose=verbose, output=out)
  File "C:\Users\usa\AppData\Roaming\Python\Python37\site-packages\pythonping\executor.py", line 224, in __init__
    self.socket = network.Socket(target, 'icmp', source=None, options=socket_options)
  File "C:\Users\usa\AppData\Roaming\Python\Python37\site-packages\pythonping\network.py", line 21, in __init__
    self.destination = socket.gethostbyname(destination)
socket.gaierror: [Errno 11001] getaddrinfo failed

标签: python-3.x

解决方案


from pythonping import ping
import socket

list = ["google.com", "usadandc2", "usadandc3", "alsdkfasd"]

for host in list:

    try:
        ip = socket.gethostbyname(host)
        result = ping(ip, count=1)
        if result.success():
            print(host, 'online')

    except socket.error:
        print(host, 'Offline')

推荐阅读