如何修改Python Ping IP地址代码以返回连通性状态值?
修改Python Ping代码返回连通状态值
你的现有代码其实已经通过布尔值返回了连通状态:True代表目标IP可连通,False代表不可连通。如果需要更直观的状态值(比如字符串、数字),可以按以下方式修改:
方案1:返回字符串形式的状态
修改ping函数的返回逻辑,直接返回"连通"或"不连通":
import subprocess import platform ip_addr = '192.168.0.10' def ping(host): """ Returns connectivity status as string. """ param = '-n' if platform.system().lower()=='windows' else '-c' command = ['ping', param, '1', host] is_reachable = subprocess.call(command) == 0 return "连通" if is_reachable else "不连通" # 调用并打印结果 print(ping(ip_addr))
方案2:返回数字形式的状态
如果需要用数字标识(比如1代表连通,0代表不连通),可以这样改:
import subprocess import platform ip_addr = '192.168.0.10' def ping(host): """ Returns 1 if reachable, 0 otherwise. """ param = '-n' if platform.system().lower()=='windows' else '-c' command = ['ping', param, '1', host] is_reachable = subprocess.call(command) == 0 return 1 if is_reachable else 0 # 调用并使用状态值 status_code = ping(ip_addr) print(f"连通状态码:{status_code}")
保留布尔值并直观输出
如果只是想在调用时更清晰地展示状态,不需要修改函数本身,直接处理返回值即可:
# 原函数不变 import subprocess import platform ip_addr = '192.168.0.10' def ping(host): """ Returns True if host responds to ping. """ param = '-n' if platform.system().lower()=='windows' else '-c' command = ['ping', param, '1', host] return subprocess.call(command) == 0 # 调用并格式化输出 connectivity = ping(ip_addr) print(f"与{ip_addr}的连通状态:{'已连通' if connectivity else '未连通'}")
内容的提问来源于stack exchange,提问作者Jun
相关产品推荐
相关产品推荐

