python异步任务队列示例

yipeiwu_com6年前Python基础

很多场景为了不阻塞,都需要异步回调机制。这是一个简单的例子,大家参考使用吧

复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import logging
import queue
import threading

def func_a(a, b):
    return a + b

def func_b():
    pass

def func_c(a, b, c):
    return a, b, c

# 异步任务队列
_task_queue = queue.Queue()

def async_call(function, callback, *args, **kwargs):
    _task_queue.put({
        'function': function,
        'callback': callback,
        'args': args,
        'kwargs': kwargs
    })

def _task_queue_consumer():
    """
    异步任务队列消费者
    """
    while True:
        try:
            task = _task_queue.get()
            function = task.get('function')
            callback = task.get('callback')
            args = task.get('args')
            kwargs = task.get('kwargs')
            try:
                if callback:
                    callback(function(*args, **kwargs))
            except Exception as ex:
                if callback:
                    callback(ex)
            finally:
                _task_queue.task_done()
        except Exception as ex:
            logging.warning(ex)

def handle_result(result):
    print(type(result), result)

if __name__ == '__main__':
    t = threading.Thread(target=_task_queue_consumer)
    t.daemon = True
    t.start()

    async_call(func_a, handle_result, 1, 2)
    async_call(func_b, handle_result)
    async_call(func_c, handle_result, 1, 2, 3)
    async_call(func_c, handle_result, 1, 2, 3, 4)

    _task_queue.join()

相关文章

python获取beautifulphoto随机某图片代码实例

Beautiful Photo!: http://www.beautifulphoto.net/ 复制代码 代码如下:import urllib2import re _random_ur...

浅谈配置OpenCV3 + Python3的简易方法(macOS)

我的电脑本来是有手动CMake+make安装的OpenCV3的,以及系统自带的python2.x,但是现在想用python3+OpenCV3。 安装Python3 brew ins...

python用plt画图时,cmp设置方法

在python,有时候是需要画图的,比如把一个矩阵用图像的形式显示,之前用的好好的,每次用plt.imshow(),都是彩色图,不知为啥,突然全是黑白图了,于是需要设置cmap的值,如下...

Python 3.6 性能测试框架Locust安装及使用方法(详解)

Python 3.6 性能测试框架Locust安装及使用方法(详解)

背景 Python3.6 性能测试框架Locust的搭建与使用 基础 python版本:python3.6 开发工具:pycharm Locust的安装与配置 点击“File”→“s...

Python3 Tkinter选择路径功能的实现方法

Python3 Tkinter选择路径功能的实现方法

效果基于Python3。 在自己写小工具的时候因为这个功能纠结了一会儿,这里写个小例子,供有需要的参考。 小例子,就是点击按钮打开路径选择窗口,选择后把值传给Entry输出。 效果预览...