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中写hive脚本

这篇文章主要介绍了如何在python中写hive脚本,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、直接执行.sql脚本 im...

对python中array.sum(axis=?)的用法介绍

对python中array.sum(axis=?)的用法介绍

根据代码中运行的结果来看,主要由以下几种: 1. sum():将array中每个元素相加的结果 2. axis对应的是维度的相加。 比如: 1、axis=0时,对饮搞得是第一个维度元素的...

django 控制页面跳转的例子

如下所示: def delEquipment(request, delip): print delip ip=delip conn= MySQLdb.connect(...

python2 中 unicode 和 str 之间的转换及与python3 str 的区别

在python2中字符串分为 unicode 和 str 类型   Str To Unicode 使用decode(), 解码   Unicode To Str 使用encode()...

11个并不被常用但对开发非常有帮助的Python库

11个并不被常用但对开发非常有帮助的Python库

近来,越来越多的数据科学家开始使用Python,我不由得想到,尽管他们从pandas、scikit-learn和numpy这些库中得到了不少好处,但是他们也许错过了一些也许较老但同样有帮...