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 操作文件 编程语言对文件系统的操作是一项必不可少的功能,各种编程语言基本上都有对文件系统的操作,最简洁的莫过于linux里面shell的操作了,其次,则是python,ru...

python fuzzywuzzy模块模糊字符串匹配详细用法

github主页 导入: >>> from fuzzywuzzy import fuzz >>> from fuzzywuzzy import p...

Python实现简单过滤文本段的方法

本文实例讲述了Python实现简单过滤文本段的方法。分享给大家供大家参考,具体如下: 一、问题: 如下文本: ## Alignment 0: score=397.0 e_value=...

python使用正则表达式的search()函数实现指定位置搜索功能

前面学习过search()可以从任意一个文本里搜索匹配的字符串,也就是说可以从任何位置里搜索到匹配的字符串。但是现实世界很复杂多变的,比如限定你只能从第100个字符的位置开始匹配,100...

django session完成状态保持的方法

django session完成状态保持的方法

本例使用登录页面演示,session的状态保持功能。 说明:因为http是无状态的,客户端请求一次页面后,就结束了,当再次访问时,服务器端并不知道浏览器此访问过什么。所以这样就需要状态保...