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实现的旋转数组功能算法。分享给大家供大家参考,具体如下: 一、题目 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 例1: 输入: [...

对python中数组的del,remove,pop区别详解

以a=[1,2,3] 为例,似乎使用del, remove, pop一个元素2 之后 a都是为 [1,3], 如下: >>> a=[1,2,3] >>...

深入浅析Python科学计算库Scipy及安装步骤

一、Scipy 入门 1.1、Scipy 简介及安装 官网:http://www.scipy.org/SciPy 安装:在C:\Python27\Scripts下打开cmd执行: 执...

python基础教程之五种数据类型详解

Python 五种数据类型 在学习一门语言的过程中,首先肯定就是要先接触到它所拥有的数据类型,Python拥有五种主要的数据类型,下面介绍一下我对这五种数据类型的理解和想法。 1.数...

python实现支持目录FTP上传下载文件的方法

本文实例讲述了python实现支持目录FTP上传下载文件的方法。分享给大家供大家参考。具体如下: 该程序支持ftp上传下载文件和目录、适用于windows和linux平台。 #!/u...