Python 多线程实例详解

yipeiwu_com5年前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操作word常见方法示例【win32com与docx模块】

本文实例讲述了Python操作word常见方法。分享给大家供大家参考,具体如下: 这里介绍两种方式: 使用win32com 使用docx 1. 使用win32com扩展包 只...

python SMTP实现发送带附件电子邮件

本文实例为大家分享了python SMTP发送带附件电子邮件的具体代码,供大家参考,具体内容如下 可采用email模块发送电子邮件附件。发送一个未知MIME类型的文件附件其基本思路如下:...

Python并行分布式框架Celery详解

Python并行分布式框架Celery详解

Celery 简介 除了redis,还可以使用另外一个神器---Celery。Celery是一个异步任务的调度工具。 Celery 是 Distributed Task Queue,分...

学习python可以干什么

python是什么? python的中文名称是蟒蛇,是一种计算机程序设计语言;是一种动态的、面向对象的脚本语言。最初是用来编写自动化脚本的,随着版本的不断更新和语言新功能的添加,越来越多...