Python 多线程实例详解

yipeiwu_com6年前Python基础

Python 多线程实例详解

多线程通常是新开一个后台线程去处理比较耗时的操作,Python做后台线程处理也是很简单的,今天从官方文档中找到了一个Demo.

实例代码:

import threading, zipfile 
 
class AsyncZip(threading.Thread): 
  def __init__(self, infile, outfile): 
    threading.Thread.__init__(self) 
    self.infile = infile 
    self.outfile = outfile 
  def run(self): 
    f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) 
    f.write(self.infile) 
    f.close() 
    print('Finished background zip of:', self.infile) 
 
background = AsyncZip('mydata.txt', 'myarchive.zip') 
background.start() 
print('The main program continues to run in foreground.') 
 
background.join()  # Wait for the background task to finish 
print('Main program waited until background was done.') 

结果:

The main program continues to run in foreground. 
Finished background zip of: mydata.txt 
Main program waited until background was done. 
Press any key to continue . . . 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python编程实现生成特定范围内不重复多个随机数的2种方法

Python编程实现生成特定范围内不重复多个随机数的2种方法

本文实例讲述了Python编程实现生成特定范围内不重复多个随机数的2种方法。分享给大家供大家参考,具体如下: 在近期进行的一个实验中,需要将数据按一定比例随机分割为两个部分。这一问题的核...

Pyqt QImage 与 np array 转换方法

项目使用Pyqt作为UI框架,使用相机线程捕捉image,并在QGraphicsView中显示,遇到以下问题: 1、采集的数据为nparray数据,需转换为QImage 转换代码如下:...

python 判断一个进程是否存在

源代码如下:复制代码 代码如下:#-*- coding:utf-8 -*- def check_exsit(process_name): import win32com.client W...

Python获取任意xml节点值的方法

本文实例讲述了Python获取任意xml节点值的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf-8 -*- import xml.dom.mini...

Python 访问限制 private public的详细介绍

 一、知识点 在一个模块中,我们可能会定义很多函数和变量。但有的函数和变量我们希望能给别人使用,有的函数和变量我们希望仅仅在模块内部使用,so? 我们可以通过定义该函...