Windows系统中使用Python与Ping命令测试网络连接状态

Python脚本,从摄像机中提取视频文件,文件保存在Wifi环境中,需要实时检测网络的连通状态,如网络连接正常,则启动下载;

Windows 系统下使用Ping 命令, 可简单方便的实现网络连接状态的检测:

ping -n 1 -w 1000 192.168.0.1

Python中使用subprocess.Popen()函数实现,代码片断如下:

def test_ip_connection(url):

  num = 1

  wait = 1000

  ping = subprocess.Popen("ping -n {} -w {} {}".format(num, wait, url),stdout=subprocess.PIPE, stderr=subprocess.PIPE) ## 这种方式,终端不会显示运行结果

  exit_code = ping.wait()

  if exit_code != 0:

    return False

  else:

    return True

如需要定期循环检查,可通过线程,加While循环体方式实现;

猜你喜欢

转载自www.cnblogs.com/sunnyhill/p/11779907.html