• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python中运行并行任务技巧

Python中运行并行任务技巧

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python 设置定时任务,python 定时任务,python定时执行任务,python 计划任务,python任务等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

示例

标准线程多进程,生产者/消费者示例:
Worker越多,问题越大
# -*- coding: utf8 -*-

import os
import time
import Queue
import threading
from PIL import Image

def create_thumbnail(filename, size=(128, 128)):
    try:
        fp, fmt = filename.rsplit('.', 1)
        im = Image.open(filename)
        im.thumbnail(size, Image.ANTIALIAS)
        im.save((fp + '_'+'x'.join(str(i) for i in size) + '.'+fmt), im.format)
        return '%s thumbnail success!' % filename
    except Exception:
        return '%s thumbnail failed!' % filename


def get_image_paths(folder):
    return [os.path.join(folder, f) for f in os.listdir(folder) if 'png' in f]


class Consumer(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue

    def run(self):
        while True:
            content = self._queue.get()
            if isinstance(content, str) and content == 'quit':
                break
            respone = create_thumbnail(content)
        print 'Bye bye!'


def Producer():
    filenames = get_image_paths('images')
    queue = Queue.Queue()
    worker_threads = build_worker_pool(queue, 4)
    start_time = time.time()

    for filename in filenames:
        queue.put(filename)
    for worker in worker_threads:
        queue.put('quit')
    for worker in worker_threads:
        worker.join()

    print time.time() - start_time


def build_worker_pool(queue, size):
    workers = []
    for _ in range(size):
        worker = Consumer(queue)
        worker.start()
        workers.append(worker)
    return workers


if __name__ == '__main__':
    Producer()
</div>

map

Map能够处理集合按顺序遍历,最终将调用产生的结果保存在一个简单的集合当中。

# -*- coding: utf8 -*-

import os
import time
from multiprocessing import Pool
from PIL import Image

def create_thumbnail(filename, size=(128, 128)):
    try:
        fp, fmt = filename.rsplit('.', 1)
        im = Image.open(filename)
        im.thumbnail(size, Image.ANTIALIAS)
        im.save((fp + '_'+'x'.join(str(i) for i in size) + '.'+fmt), im.format)
        return '%s thumbnail success!' % filename
    except Exception:
        return '%s thumbnail failed!' % filename


def get_image_paths(folder):
    return [os.path.join(folder, f) for f in os.listdir(folder) if 'png' in f]


def main():
    filenames = get_image_paths('images')
    start_time = time.time()
   
    pool = Pool(4)
    pool.map(create_thumbnail, filenames)
    pool.close()
    pool.join()

    print time.time() - start_time


if __name__ == '__main__':
    main()
</div>

</div>

您可能想查找下面的文章:

  • Python实现定时任务
  • 用Python编写简单的定时器的方法
  • 用Python编写简单的定时器的方法
  • Python中运行并行任务技巧

相关文章

  • python常用知识梳理(必看篇)
  • 使用python实现拉钩网上的FizzBuzzWhizz问题示例
  • Python对文件操作知识汇总
  • Win7下搭建python开发环境图文教程(安装Python、pip、解释器)
  • Python获取Windows或Linux主机名称通用函数分享
  • 详解python3百度指数抓取实例
  • Python多线程结合队列下载百度音乐的方法
  • Python 元类使用说明
  • Python @property装饰器原理解析
  • Python使用poplib模块和smtplib模块收发电子邮件的教程

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python使用htpasswd实现基本认证授权的例子
    • jupyter安装小结
    • 用实例分析Python中method的参数传递过程
    • Python用list或dict字段模式读取文件的方法
    • Python标准库os.path包、glob包使用实例
    • Python内置数据结构与操作符的练习题集锦
    • python通过apply使用元祖和列表调用函数实例
    • 详解在Python程序中使用Cookie的教程
    • 跟老齐学Python之再深点,更懂list
    • 使用Python的Flask框架表单插件Flask-WTF实现Web登录验证

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有