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 相关文章推荐
在Docker上开始部署Python应用的教程
Apr 17 Python
Python基于DES算法加密解密实例
Jun 03 Python
13个最常用的Python深度学习库介绍
Oct 28 Python
Python创建二维数组实例(关于list的一个小坑)
Nov 07 Python
Python将图片转换为字符画的方法
Jun 16 Python
Python 加密与解密小结
Dec 06 Python
安装完Python包然后找不到模块的解决步骤
Feb 13 Python
Python使用pdb调试代码的技巧
May 03 Python
使用Keras建立模型并训练等一系列操作方式
Jul 02 Python
Python实现京东抢秒杀功能
Jan 25 Python
python 经纬度求两点距离、三点面积操作
Jun 03 Python
为了顺利买到演唱会的票用Python制作了自动抢票的脚本
Oct 16 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&MYSQL服务器配置说明
2006/10/09 PHP
PHP实现加密的几种方式介绍
2015/02/22 PHP
HTML中嵌入PHP的简单方法
2016/02/16 PHP
PHP连接MySQL数据库的三种方式实例分析【mysql、mysqli、pdo】
2019/11/04 PHP
PHP设计模式(九)外观模式Facade实例详解【结构型】
2020/05/02 PHP
20个非常棒的Jquery实用工具 国外文章
2010/01/01 Javascript
Javascript 面向对象 对象(Object)
2010/05/13 Javascript
遍历jquery对象的代码分享
2011/11/02 Javascript
jQuery cdn使用介绍
2013/05/08 Javascript
JavaScript输入邮箱自动提示实例代码
2014/01/13 Javascript
jQuery中detach()方法用法实例
2014/12/25 Javascript
js实现用户离开页面前提示是否离开此页面的方法(包括浏览器按钮事件)
2015/07/18 Javascript
js支持键盘控制的左右切换立体式图片轮播效果代码分享
2015/08/26 Javascript
用iframe实现不刷新整个页面上传图片的实例
2016/11/18 Javascript
多个上传文件用js验证文件的格式和大小的方法(推荐)
2017/03/09 Javascript
jquery中封装函数传递当前元素的方法示例
2017/05/05 jQuery
vue 音乐App QQ音乐搜索列表最新接口跨域设置方法
2018/09/25 Javascript
jQuery中实现text()的方法
2019/04/04 jQuery
详解微信小程序的不同函数调用的几种方法
2019/05/08 Javascript
node.js命令行教程图文详解
2019/05/27 Javascript
JS实现盒子拖拽效果
2020/02/06 Javascript
vue 路由缓存 路由嵌套 路由守卫 监听物理返回操作
2020/08/06 Javascript
JavaScript实现点击图片换背景
2020/11/20 Javascript
[02:00]DOTA2英雄COSPLAY闹市街头巡游助威2015国际邀请赛
2015/08/02 DOTA
从零学Python之引用和类属性的初步理解
2014/05/15 Python
Python中的tuple元组详细介绍
2015/02/02 Python
Python使用xlwt模块操作Excel的方法详解
2018/03/27 Python
实例分析python3实现并发访问水平切分表
2018/09/29 Python
利用HTML5+CSS3实现3D转换效果实例详解
2017/05/02 HTML / CSS
HTML5操作WebSQL数据库的实例代码
2017/08/26 HTML / CSS
美国男女折扣服饰百货连锁店:Stein Mart
2017/05/02 全球购物
eBay爱尔兰站:eBay.ie
2019/08/09 全球购物
2015年酒店工作总结范文
2015/04/07 职场文书
运动会报道稿大全
2015/07/23 职场文书
幽默导游词应该怎么写?
2019/08/26 职场文书
Python实现Hash算法
2022/03/18 Python