易Python的异步。 precompiler? [英] Easy Python ASync. Precompiler?

查看:122
本文介绍了易Python的异步。 precompiler?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个这样的IO重功能:

imagine you have an io heavy function like this:

def getMd5Sum(path):
    with open(path) as f:
        return md5(f.read()).hexdigest()

你认为Python是非常灵活,允许code这样的(注意$):

Do you think Python is flexible enough to allow code like this (notice the $):

def someGuiCallback(filebutton):
    ...
    path = filebutton.getPath()
    md5sum = $getMd5Sum()
    showNotification("Md5Sum of file: %s" % md5sum)
    ...

要执行这样的:

def someGuiCallback_1(filebutton):
    ...
    path = filebutton.getPath()
    Thread(target=someGuiCallback_2, args=(path,)).start()

def someGuiCallback_2(path):
    md5sum = getMd5Sum(path)
    glib.idle_add(someGuiCallback_3, md5sum)

def someGuiCallback_3(md5sum):
    showNotification("Md5Sum of file: %s" % md5sum)
    ...

(glib.idle_add只是按下一个功能到主线程队列)

(glib.idle_add just pushes a function onto the queue of the main thread)

我已经想过使用decoraters,但他们不允许我去调用后访问该功能的内容。 (该部分showNotification)

I've thought about using decoraters, but they don't allow me to access the 'content' of the function after the call. (the showNotification part)

我想我可以写一个编译器来更改执行前的code,但它并不像缝的最佳解决方案。

I guess I could write a 'compiler' to change the code before execution, but it doesn't seam like the optimal solution.

你有什么想法,对如何做这样的事情上面?

Do you have any ideas, on how to do something like the above?

推荐答案

当然,你可以从装饰接入功能code(已编译),拆卸和攻击它。你甚至可以访问它的定义模块的源并重新编译。但我认为这是没有必要的。下面是一个使用装饰发生器,其中收益语句作为同步和异步部分之间的分隔符的例子:

Sure you can access function code (already compiled) from decorator, disassemble and hack it. You can even access the source of module it's defined in and recompile it. But I think this is not necessary. Below is an example using decorated generator, where yield statement serves as a delimiter between synchronous and asynchronous parts:

from threading import Thread
import hashlib

def async(gen):
    def func(*args, **kwargs):
        it = gen(*args, **kwargs)
        result = it.next()
        Thread(target=lambda: list(it)).start()
        return result
    return func

@async
def test(text):
    # synchronous part (empty in this example)
    yield # Use "yield value" if you need to return meaningful value
    # asynchronous part[s]
    digest = hashlib.md5(text).hexdigest()
    print digest

这篇关于易Python的异步。 precompiler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆