对python判断ip是否可达的实例详解

yipeiwu_com6年前Python基础

python中使用subprocess来使用shell

关于threading的用法

from __future__ import print_function
import subprocess
import threading

def is_reachable(ip):
  if subprocess.call(["ping", "-c", "2", ip])==0:#只发送两个ECHO_REQUEST包
    print("{0} is alive.".format(ip))
  else:
    print("{0} is unalive".format(ip))
if __name__ == "__main__":
  ips = ["www.baidu.com","192.168.0.1"]
  threads = []
  for ip in ips:
    thr = threading.Thread(target=is_reachable, args=(ip,))#参数必须为tuple形式
    thr.start()#启动
    threads.append(thr)
  for thr in threads:
    thr.join()

改良 :使用Queue来优化(FIFO)

from __future__ import print_function
import subprocess
import threading
from Queue import Queue
from Queue import Empty

def call_ping(ip):
  if subprocess.call(["ping", "-c", "2", ip])==0:
    print("{0} is reachable".format(ip))
  else:
    print("{0} is unreachable".format(ip))


def is_reachable(q):
  try:
    while True:
      ip = q.get_nowait()#当队列为空,不等待
      call_ping(ip)
  except Empty:
    pass


def main():
  q = Queue()
  args = ["www.baidu.com", "www.sohu.com", "192.168.0.1"]
  for arg in args:
    q.put(arg)

  threads = []
  for i in range(10):
    thr = threading.Thread(target=is_reachable, args=(q,))
    thr.start()
    threads.append(thr)
  for thr in threads:
    thr.join()

if __name__ == "__main__":
  main()

以上这篇对python判断ip是否可达的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 实时得到cpu和内存的使用情况方法

python 实时得到cpu和内存的使用情况方法

如下所示: #先下载psutil库:pip install psutil import psutil import os,datetime,time def getMemCpu()...

Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍

1. 创建映射类的实例(Instance) 前面介绍了如何将数据库实体表映射到Python类上,下面我们可以创建这个类的一个实例(Instance),我们还是以前一篇文章的User类为例...

详解numpy矩阵的创建与数据类型

详解numpy矩阵的创建与数据类型

Numpy是python常用的一个类库,在python的使用中及其常见,广泛用在矩阵的计算中,numpy对矩阵的操作与纯python比起来速度有极大的差距。 一、 构造矩阵 矩阵的构造...

python3中获取文件当前绝对路径的两种方法

方法1: import sys print(sys.argv) 得到文件当前绝对路径字符串的一个列表 ['D:/pycharm/PracticeProject/ClientSe...

python-序列解包(对可迭代元素的快速取值方法)

一般情况下 x,y,z = 1,2,3 print("x:",x) print("y:",y) print("z:",z) #运行结果 x: 1 y: 2 z: 3 对元祖序...