对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与php实现分割文件代码

python与php实现分割文件代码

前两天有个朋友说,想实现一个文本文件按照固定行数进行分割成多个文本文件,却不知如何实现。如果数据量小手动分割下就好了,如果数据量很大的话手动完成实在太耗费人力了,也不现实。那么就需要借助...

Python断言assert的用法代码解析

在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误)。这时候断言assert 就显得非常有用。 python assert断言是声明布尔值必须为真的判定,如果...

python使用super()出现错误解决办法

python使用super()出现错误解决办法 当我们在python的子类中调用父类的方法时,会用到super(),不过我遇到了一个问题,顺便记录一下。 比如,我写了如下错误代码:...

python列表每个元素同增同减和列表元素去空格的实例

python列表每个元素同增同减和列表元素去空格的实例

如下所示: import os var = [1, 2, 3] data = [x*2 for x in var] print (data) two = [[i, i**2] f...

Windows系统下多版本pip的共存问题详解

Windows系统下多版本pip的共存问题详解

前言 可能很多人一看到这个标题直接就关闭了,这么简单和low的问题有必要说出来吗?一看就知道是个Python的小白。如果你是这么想的话,那么就没有必要看下去了,因为对你来说也没有...