Python实现模拟分割大文件及多线程处理的方法

yipeiwu_com7年前Python基础

本文实例讲述了Python实现模拟分割大文件及多线程处理的方法。分享给大家供大家参考,具体如下:

#!/usr/bin/env python
#--*-- coding:utf-8 --*--
from random import randint
from time import ctime
from time import sleep
import queue
import threading
class MyTask(object):
  """具体的任务类"""
  def __init__(self, name):
    self.name = name
    self._work_time = randint(1, 5)
  def work(self):
    print("Task %s is start : %s, sleep time= %d" % (self.name, ctime(), self._work_time))
    sleep(self._work_time)
    print("Task %s is end : %s" % (self.name, ctime()))
class MyThread(threading.Thread):
  """多线程的类"""
  def __init__(self, my_queue):
    self.my_queue = my_queue
    super(MyThread, self).__init__()
  def run(self):
    while True:
      if self.my_queue.qsize() > 0:
        self.my_queue.get().work()
      else:
        break
def print_split_line(num=30):
  print("*" * num)
if __name__ == "__main__":
  print_split_line()
  import my_read_file
  # 分割文件
  sf = my_read_file.SplitFiles(r"F:\multiple_thread_read_file.txt", line_count=300)
  file_num = sf.split_file()
  queue_length = file_num
  my_queue = queue.LifoQueue(queue_length)
  threads = []
  for i in range(queue_length):
    file_name = sf.get_part_file_name(i)
    mt = MyTask(file_name)
    my_queue.put_nowait(mt)
  for i in range(queue_length):
    mtd = MyThread(my_queue)
    threads.append(mtd)
  for i in range(queue_length):
    threads[i].start()
  for i in range(queue_length):
    threads[i].join()
  print_split_line()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

详解PyTorch中Tensor的高阶操作

详解PyTorch中Tensor的高阶操作

条件选取:torch.where(condition, x, y) → Tensor 返回从 x 或 y 中选择元素的张量,取决于 condition 操作定义: 举个例子:...

在Python中使用dict和set方法的教程

在Python中使用dict和set方法的教程

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 举个例子,假设要...

python循环定时中断执行某一段程序的实例

问题说明 最近在写爬虫,由于单个账号访问频率太高会被封,所以需要在爬虫执行一段时间间隔后自己循环切换账号 所以就在想,有没有像单片机那样子设置一个定时中断,再定义一个中断入口,这样子每隔...

Python实现E-Mail收集插件实例教程

Python实现E-Mail收集插件实例教程

__import__函数 我们都知道import是导入模块的,但是其实import实际上是使用builtin函数import来工作的。在一些程序中,我们可以动态去调用函数,如果我们知道...

python3.8下载及安装步骤详解

python3.8下载及安装步骤详解

1.操作系统:Windows7 64bit Python版本:3.8下载地址:https://www.python.org/downloads/release/python-380/,选...