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 提取key 为中文的json 串方法

示例: # -*- coding:utf-8 -*- import json strtest = {"中故宫":"好地方","天涯":"北京"} print strtest ###...

Python流程控制 while循环实现解析

Python流程控制 while循环实现解析

一、语法 while 条件: 执行代码 while就是当的意思,它指当其后面的条件成立,就执行while下面的代码。 例:写一个从0打印到10的程序 count = 0 whi...

浅析python中numpy包中的argsort函数的使用

浅析python中numpy包中的argsort函数的使用

概述 argsort()函数在模块numpy.core.fromnumeric中。 在python中排序数组,或者获取排序顺序的时候,我们常常使用numpy包的argsort函数来完成。...

python版学生管理系统

python版学生管理系统

写一个学生管理系统,最好用python。 我都没学过python呢,只好开始临时抱佛脚,再到网上找找有没有例子看看,下面是我参照另一个博主写的,中间有一些和我不能融合的错误,我已经解决了...

Python 获取命令行参数内容及参数个数的实例

执行python脚本的时候,有时需要获取命令行参数的相关信息。C语言通过argc和argv来获取参数的个数和参数的内容,python中通过sys模块的argv来获取参数的内容,使用len...