溫馨提示×

Python ping命令返回值怎么處理

小樊
139
2024-12-07 13:23:39
欄目: 編程語言

在Python中,你可以使用subprocess模塊來執行ping命令并處理返回值

import subprocess

def ping(host, timeout=1, count=4):
    try:
        # 使用ping命令(Windows系統使用'-n',Linux和macOS系統使用'-c')
        command = ['ping', '-c', str(count), host] if platform.system().lower() != 'windows' else ['ping', '-n', str(count), host]
        
        # 執行ping命令
        output = subprocess.check_output(command, stderr=subprocess.STDOUT, timeout=timeout)
        
        # 將輸出轉換為字符串并返回
        return output.decode('utf-8')
    except subprocess.TimeoutExpired:
        return f"請求超時,目標主機:{host}"
    except subprocess.CalledProcessError as e:
        return f"請求失敗,目標主機:{host}\n錯誤信息:{e.output.decode('utf-8')}"
    except Exception as e:
        return f"發生未知錯誤,目標主機:{host}\n錯誤信息:{str(e)}"

# 使用示例
host = "www.example.com"
result = ping(host)
print(result)

這個示例中的ping函數接受一個主機名(或IP地址)作為參數,并設置了超時時間和ping次數。它使用subprocess.check_output()執行ping命令,并通過捕獲異常來處理可能的錯誤。最后,它將輸出轉換為字符串并返回。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女