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

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

相关文章

Numpy中stack(),hstack(),vstack()函数用法介绍及实例

1.stack()函数 函数原型为:stack(arrays,axis=0),arrays可以传数组和列表。axis的含义我下面会讲解,我们先来看个例子,然后我会分析输出结果。 im...

Python学习笔记_数据排序方法

1. 原地排序:采用sort()方法,按照指定的顺序排列数据后用排序后的数据替换原来的数据(原来的顺序丢失),如: 复制代码 代码如下:>>> data1=[4,2,6...

python实现文件名批量替换和内容替换

指定文件夹,指定文件类型,替换该文件夹下全部文件的内容。 注意在window下的读写内容需要指定编码,还需要在文件头指定#coding:utf-8 编码,避免出现编码问题。复制代码 代码...

Python Django Cookie 简单用法解析

Python Django Cookie 简单用法解析

home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT...

Python编写生成验证码的脚本的教程

在web开发中经常用到验证码,为了防止机器人注册或者恶意登陆和查询等,作用不容小觑 但是验证码其实不是一个函数就能搞定的,它需要生成图片和水印,其实每种语言都有相关的函数生成图片和文字水...