对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设计】。

相关文章

使用NumPy和pandas对CSV文件进行写操作的实例

数组存储成CSV之类的区隔型文件: 下面代码给随机数生成器指定种子,并生成一个3*4的NumPy数组 将一个数组元素的值设为NaN: In [26]: import numpy a...

Pycharm取消py脚本中SQL识别的方法

Pycharm取消py脚本中SQL识别的方法

Pycharm默认可以识别py脚本中的SQL语句,本身很不错,但当SQL拼接时就显示的代码特别难看,找了好久,终于知道怎么关闭SQL识别功能了。 如下图,把勾去掉就可以了。 以上这篇P...

Python的SQLAlchemy框架使用入门

数据库表是一个二维表,包含多行多列。把一个表的内容用Python的数据结构表示出来的话,可以用一个list表示多行,list的每一个元素是tuple,表示一行记录,比如,包含id和nam...

常见的python正则用法实例讲解

下面列出Python正则表达式的几种匹配用法: 此外,关于正则的一切http://deerchao.net/tutorials/regex/regex.htm  1.测试正则表...

pandas DataFrame行或列的删除方法的实现示例

pandas DataFrame行或列的删除方法的实现示例

此文我们继续围绕DataFrame介绍相关操作。 平时在用DataFrame时候,删除操作用的不太多,基本是从源DataFrame中筛选数据,组成一个新的DataFrame再继续操作。...