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

yipeiwu_com5年前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实现将读入的多维list转为一维list的方法

第一种:使用extend() >>> lines = open('test.txt').readlines() >>> lines ['1\n',...

python使用if语句实现一个猜拳游戏详解

python使用if语句实现一个猜拳游戏详解

任务要求 在控制台中提示输入石头、剪刀、布,按回车键,然后给出游戏结果。 分析 我们知道在游戏规则中,石头克剪刀,剪刀克布,布克石头。但是这在计算机中并不是很好直接的表示,因此我们分别...

Python 限定函数参数的类型及默认值方式

python作为一门动态语言,在使用变量之前是不需要进行定义,而是通过动态绑定的方法将变量绑定为某种类型。这样做为我们使用变量时提供了方便,但有时也给我们使用变量时造成了一定的困扰,例如...

python的等深分箱实例

python的等深分箱实例

背景 当前很多文章尝试过最优分箱,python上也有cut等方法进行等宽分箱。为了方便日后输出结果以及分箱要求。做一个简单的轮子以供大家日后使用。很多能用其他轮子的地方也没有多余出力,也...

Python编写一个优美的下载器

Python编写一个优美的下载器

本文实例为大家分享了Python编写下载器的具体代码,供大家参考,具体内容如下 #!/bin/python3 # author: lidawei # create: 2016-...