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 . . . 

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

相关文章

更新pip3与pyttsx3文字语音转换的实现方法

我使用的python版本是3.5.2 今天想做个语音读取的小脚本,在网上查了一下发现python里有个pyttsx可以识别文字, 打算通过pip3 install pyttsx安装包,结...

Python 实现字符串中指定位置插入一个字符

如下所示: str_1='wo shi yi zhi da da niu/n'str_list=list(str_1) nPos=str_list.index('/') str_li...

Django中间件实现拦截器的方法

Django中间件实现拦截器的方法

1.前言 JavaWeb Struts2的拦截器我们都能很熟悉,在请求交给Action处理之前,先在拦截器中处理,处理完之后再交给Action。 在Django中如何实现相同的效果...

Python中函数的返回值示例浅析

前言: 前面我们介绍了简单的介绍了函数和函数的参数,今天我们来说一下Python中函数的返回值。 函数的返回值:函数运算的结果,需要进一步的操作时,给一个返回值return用来返回函数...

Python3.x和Python2.x的区别介绍

1.性能Py3.0运行 pystone benchmark的速度比Py2.5慢30%。Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可以取得很好的优化结果。Py3.1性能...