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变量、自定义函数用法。分享给大家供大家参考,具体如下: 不管你学什么编程语言 都逃不出如下套路: 1、怎么定义变量?是否有数据类型,怎么在控制台输出? 2、怎...

Python对文件和目录进行操作的方法(file对象/os/os.path/shutil 模块)

使用Python过程中,经常需要对文件和目录进行操作。所有file类/os/os.path/shutil模块时每个Python程序员必须学习的。 下面通过两段code来对其进行学习。 1...

Python中集合的内建函数和内建方法学习教程

Python中集合的内建函数和内建方法学习教程

集合内建函数和内建方法 (1)标准类型函数        len():把集合作为参数传递给内建函数 len(),返回集合的基数...

python如何读取bin文件并下发串口

下面是实现代码 # coding:utf-8 import time, serial from struct import * import binascii file = ope...

django2 快速安装指南分享

1. 安装 作为一个 Python Web 框架,Django需要Python的支持。请参阅 我可以在Django中使用哪些Python版本?了解详情。Python包含一个名为SQLit...