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的staticmethod与classmethod实现实例代码

本文源于一时好奇,想要弄清出python的staticmethod()这一builtin方法的实现,查了一些资料(主要是python官方手册了)汇集于此 python在类中,有三种调用m...

django限制匿名用户访问及重定向的方法实例

前言 大家应该都遇到过,在某些页面中,我们不希望匿名用户能够访问,例如个人页面等,这种页面只允许已经登录的用户去访问,在django中,我们也有比较多的方式去实现。 最简单的,我们在v...

Linux CentOS7下安装python3 的方法

在CentOS7下,默认安装的就是python2.7,我现在来教大家如何安装python3: 1、首先安装python3.6可能使用的依赖 # yum -y install open...

python模拟鼠标点击和键盘输入的操作

python模拟鼠标点击和键盘输入的操作

所有代码都是网上百度出来的,通过个人实践找到适合自己的。 采用的python 库是 pymouse、pykeyboard 安装时直接pip安装的,pip install PyU...

Python3控制路由器——使用requests重启极路由.py

通过本文给大家介绍Python3控制路由器——使用requests重启极路由.py的相关知识,代码写了相应的注释,以后再写成可以方便调用的模块。 用fiddler抓包可以看到很多HTTP...