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的gevent框架下执行异步的Solr查询的教程

 我经常需要用Python与solr进行异步请求工作。这里有段代码阻塞在Solr http请求上, 直到第一个完成才会执行第二个请求,代码如下:   impor...

Python求两个list的差集、交集与并集的方法

本文实例讲述了Python求两个list的差集、交集与并集的方法。分享给大家供大家参考。具体如下: list就是指两个数组之间的差集,交集,并集了,这个小学数学时就学过的东西,下面就以实...

解决Tensorflow安装成功,但在导入时报错的问题

在Mac上按照官网教程安装成功tensor flow后,但在程序中导入时,仍然报错,包括但不限于以下两个错误。对于这种错误,原因主要在于Mac内默认的python库比较老了,即便通过pi...

python无限生成不重复(字母,数字,字符)组合的方法

使用python自带的itertools模块 调用其product函数 传入我们想组合生成的字符数据 便会源源不断的生成组合 而且不会重复 repeat参数指定生成多少位 impor...

Python + Flask 实现简单的验证码系统

Python + Flask 实现简单的验证码系统

一、写在前面   现在无论大大小小的网站,基本上都会使用验证码,登录的时候要验证,下载的时候要验证,而使用的验证码也从那些简简单单的字符图形验证码“进化”成了需要进行图文识别的验证码、...