python开发之基于thread线程搜索本地文件的方法


Posted in Python onNovember 11, 2015

本文实例讲述了python开发之基于thread线程搜索本地文件的方法。分享给大家供大家参考,具体如下:

先来看看运行效果图:

python开发之基于thread线程搜索本地文件的方法

利用多个线程处理搜索的问题,我们可以发现他很快....

下面是代码部分:

# A parallelized "find(1)" using the thread module.
# This demonstrates the use of a work queue and worker threads.
# It really does do more stats/sec when using multiple threads,
# although the improvement is only about 20-30 percent.
# (That was 8 years ago. In 2002, on Linux, I can't measure
# a speedup. :-( )
# I'm too lazy to write a command line parser for the full find(1)
# command line syntax, so the predicate it searches for is wired-in,
# see function selector() below. (It currently searches for files with
# world write permission.)
# Usage: parfind.py [-w nworkers] [directory] ...
# Default nworkers is 4
import sys
import getopt
import time
import os
from stat import *
import _thread as thread
# Work queue class. Usage:
#  wq = WorkQ()
#  wq.addwork(func, (arg1, arg2, ...)) # one or more calls
#  wq.run(nworkers)
# The work is done when wq.run() completes.
# The function calls executed by the workers may add more work.
# Don't use keyboard interrupts!
class WorkQ:
  # Invariants:
  # - busy and work are only modified when mutex is locked
  # - len(work) is the number of jobs ready to be taken
  # - busy is the number of jobs being done
  # - todo is locked iff there is no work and somebody is busy
  def __init__(self):
    self.mutex = thread.allocate()
    self.todo = thread.allocate()
    self.todo.acquire()
    self.work = []
    self.busy = 0
  def addwork(self, func, args):
    job = (func, args)
    self.mutex.acquire()
    self.work.append(job)
    self.mutex.release()
    if len(self.work) == 1:
      self.todo.release()
  def _getwork(self):
    self.todo.acquire()
    self.mutex.acquire()
    if self.busy == 0 and len(self.work) == 0:
      self.mutex.release()
      self.todo.release()
      return None
    job = self.work[0]
    del self.work[0]
    self.busy = self.busy + 1
    self.mutex.release()
    if len(self.work) > 0:
      self.todo.release()
    return job
  def _donework(self):
    self.mutex.acquire()
    self.busy = self.busy - 1
    if self.busy == 0 and len(self.work) == 0:
      self.todo.release()
    self.mutex.release()
  def _worker(self):
    time.sleep(0.00001)   # Let other threads run
    while 1:
      job = self._getwork()
      if not job:
        break
      func, args = job
      func(*args)
      self._donework()
  def run(self, nworkers):
    if not self.work:
      return # Nothing to do
    for i in range(nworkers-1):
      thread.start_new(self._worker, ())
    self._worker()
    self.todo.acquire()
# Main program
def main():
  nworkers = 4
  #print(getopt.getopt(sys.argv[1:], '-w:'))
  opts, args = getopt.getopt(sys.argv[1:], '-w:')
  for opt, arg in opts:
    if opt == '-w':
      nworkers = int(arg)
  if not args:
    #print(os.curdir)
    args = [os.curdir]
  wq = WorkQ()
  for dir in args:
    wq.addwork(find, (dir, selector, wq))
  t1 = time.time()
  wq.run(nworkers)
  t2 = time.time()
  sys.stderr.write('Total time %r sec.\n' % (t2-t1))
# The predicate -- defines what files we look for.
# Feel free to change this to suit your purpose
def selector(dir, name, fullname, stat):
  # Look for world writable files that are not symlinks
  return (stat[ST_MODE] & 0o002) != 0 and not S_ISLNK(stat[ST_MODE])
# The find procedure -- calls wq.addwork() for subdirectories
def find(dir, pred, wq):
  try:
    names = os.listdir(dir)
  except os.error as msg:
    print(repr(dir), ':', msg)
    return
  for name in names:
    if name not in (os.curdir, os.pardir):
      fullname = os.path.join(dir, name)
      try:
        stat = os.lstat(fullname)
      except os.error as msg:
        print(repr(fullname), ':', msg)
        continue
      if pred(dir, name, fullname, stat):
        print(fullname)
      if S_ISDIR(stat[ST_MODE]):
        if not os.path.ismount(fullname):
          wq.addwork(find, (fullname, pred, wq))
# Call the main program
main()

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python中用Ctrl+C终止多线程程序的问题解决
Mar 30 Python
python二叉树遍历的实现方法
Nov 21 Python
Python中用sleep()方法操作时间的教程
May 22 Python
使用Python对Excel进行读写操作
Mar 30 Python
用pickle存储Python的原生对象方法
Apr 28 Python
Python机器学习算法之k均值聚类(k-means)
Feb 23 Python
PyQt5每天必学之像素图控件QPixmap
Apr 19 Python
《与孩子一起学编程》python自测题
May 27 Python
对Tensorflow中的变量初始化函数详解
Jul 27 Python
Python 使用指定的网卡发送HTTP请求的实例
Aug 21 Python
opencv实现简单人脸识别
Feb 19 Python
python多线程实现代码(模拟银行服务操作流程)
Jan 13 Python
python开发之tkinter实现图形随鼠标移动的方法
Nov 11 #Python
Python复制文件操作实例详解
Nov 10 #Python
Python中对元组和列表按条件进行排序的方法示例
Nov 10 #Python
Python 文件管理实例详解
Nov 10 #Python
Python list操作用法总结
Nov 10 #Python
python控制台中实现进度条功能
Nov 10 #Python
使用Python发送各种形式的邮件的方法汇总
Nov 09 #Python
You might like
PHP源码之 ext/mysql扩展部分
2009/07/17 PHP
并发下常见的加锁及锁的PHP具体实现代码
2010/10/12 PHP
php中实现记住密码自动登录的代码
2011/03/02 PHP
深入理解curl类,可用于模拟get,post和curl下载
2013/06/08 PHP
php递归函数怎么用才有效
2018/02/24 PHP
动态改变textbox的宽高的js
2006/10/26 Javascript
DOM 基本方法
2009/07/18 Javascript
js常用数组操作方法简明总结
2014/06/20 Javascript
理解Javascript图片预加载
2016/02/23 Javascript
分享12个实用的jQuery代码片段
2016/03/09 Javascript
JQuery validate插件Remote用法大全
2016/05/15 Javascript
利用React-router+Webpack快速构建react程序
2016/10/27 Javascript
有趣的bootstrap走动进度条
2016/12/01 Javascript
详解nodejs 文本操作模块-fs模块(二)
2016/12/22 NodeJs
详解vue.js+UEditor集成 [前后端分离项目]
2017/07/07 Javascript
Vue结合SignalR实现前后端实时消息同步
2017/09/19 Javascript
ionic3+Angular4实现接口请求及本地json文件读取示例
2017/10/11 Javascript
vue点击按钮实现简单页面的切换
2020/09/08 Javascript
pygame播放音乐的方法
2015/05/19 Python
Python抓取百度查询结果的方法
2015/07/08 Python
Python内置方法实现字符串的秘钥加解密(推荐)
2019/12/09 Python
python中round函数保留两位小数的方法
2020/12/04 Python
基于CSS3制作立体效果导航菜单
2016/01/12 HTML / CSS
HTML5 贪吃蛇游戏实现思路及源代码
2013/09/03 HTML / CSS
乐天旅游台湾网站:Rakuten Travel TW
2017/06/01 全球购物
如何选择使用结构还是类
2014/05/30 面试题
大学同学聚会邀请函
2014/01/19 职场文书
村党支部换届选举方案
2014/05/02 职场文书
青年安全生产示范岗事迹材料
2014/05/04 职场文书
大专毕业生求职信
2014/07/05 职场文书
七一建党日演讲稿
2014/09/05 职场文书
中学生检讨书范文
2014/11/03 职场文书
学术会议邀请函
2015/01/30 职场文书
小学学习委员竞选稿
2015/11/20 职场文书
中国式结婚:司仪主持词(范文)
2019/07/25 职场文书
CentOS7安装GlusterFS集群以及相关配置
2022/04/12 Servers