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中的for循环

python中的for循环

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 语法: for循环的语法格式如下: for iterating_var in sequence:...

Pycharm 实现下一个文件引用另外一个文件的方法

Pycharm 实现下一个文件引用另外一个文件的方法

换了个电脑重新安装了Anaconda和Pycharm,把原来的项目导进去之后,有几个文件用到了另外几个文件里面的东西,引用老是报错。 如下图的位置,我这里已经修复了所以没看到标红啦:...

tesserocr与pytesseract模块的使用方法解析

1.tesserocr的使用 #从文件识别图像字符 In [7]: tesserocr.file_to_text('image.png') Out[7]: 'Python3WebSp...

Python 检查数组元素是否存在类似PHP isset()方法

PHP中有isset方法来检查数组元素是否存在,在Python中无对应函数。 Python的编程理念是“包容错误”而不是“严格检查”。举例如下: 复制代码 代码如下: Look befo...

python2和python3应该学哪个(python3.6与python3.7的选择)

首先先说一下python2与python3的选择 许多刚入门 Python 的朋友都在纠结的的问题是:我应该选择学习 python2 还是 python3? 对此,回答是:果断 Pyth...