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

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

相关文章

django重新生成数据库中的某张表方法

今天有碰到这种情况,数据库中有张表没办法通过migration来更改, migrate时报 django.db.utils.OperationalError: (1050, “Table...

Python中一般处理中文的几种方法

Python中的中文是个很头痛的问题,Python2和Python3都会出现,而且py2中出现的概率要大些。  有一道面试题: Python中如何处理中文问题,能想到的就是以下...

Python如何实现守护进程的方法示例

场景设置: 你编写了一个python服务程序,并且在命令行下启动,而你的命令行会话又被终端所控制,python服务成了终端程序的一个子进程。因此如果你关闭了终端,这个命令行程序也会随之关...

Python脚本修改阿里云的访问控制列表的方法

需求 对于部署在阿里云上的重要系统一般是不让其他人访问的,所以会在负载均衡(SLB)上加上访问控制列表。而使用ASDL拨号上网的宽带来说一般公网IP都不会固定的,会随时变更公网IP,所...

Python实现Linux监控的方法

工作原理:基于/proc 文件系统 Linux 系统为管理员提供了非常好的方法,使其可以在系统运行时更改内核,而不需要重新引导内核系统,这是通过/proc 虚拟文件系统实现的。/proc...