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数据类型判断及列表脚本操作

浅谈Python数据类型判断及列表脚本操作

数据类型判断 在python(版本3.0以上)使用变量,并进行值比较时。有时候会出现以下错误: TypeError: unorderable types: NoneType() <...

PyCharm2018 安装及破解方法实现步骤

PyCharm2018 安装及破解方法实现步骤

PyCharm就是Python语言开发中一个很受欢迎的IDE,界面类似于visual studio,android studio,集成的功能也很多。 1>. 安装 首先要...

Python装饰器的执行过程实例分析

本文实例分析了Python装饰器的执行过程。分享给大家供大家参考,具体如下: 今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭...

Python使用PDFMiner解析PDF代码实例

Python使用PDFMiner解析PDF代码实例

近期在做爬虫时有时会遇到网站只提供pdf的情况,这样就不能使用scrapy直接抓取页面内容了,只能通过解析PDF的方式处理,目前的解决方案大致只有pyPDF和PDFMiner。因为据说P...

快速解决docker-py api版本不兼容的问题

docker提供了Python、Go等编程语言的api。最近打算用docker SDK for Python(以下简称docker-py)做点东西,本来以为按照官网上的步骤安装很简单,p...