国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
ASPN : Python Cookbook : [Twisted] From block...

## version 1.1, changed according to the suggestions in the comments            from twisted.internet import reactor, defer            from twisted.python import threadable; threadable.init(1)            import sys, time            ## the wrong way            def callInThread(func, *args):            """Takes a blocking function an converts it into a deferred-valued            function running in a separate thread.            """            de = defer.Deferred()            de.addCallback(func)            reactor.callInThread(de.callback, *args)            return de            deferred = callInThread.__get__ # decorator associated to callInThread            # the right way            from twisted.internet.threads import deferToThread            deferred = deferToThread.__get__            ## example code            def print_(result):            print result            def running():            "Prints a few dots on stdout while the reactor is running."            sys.stdout.write("."); sys.stdout.flush()            reactor.callLater(.1, running)            @deferred            def sleep(sec):            "A blocking function magically converted in a non-blocking one."            print ‘start sleep %s‘ % sec            time.sleep(sec)            print ‘\nend sleep %s‘ % sec            return "ok"            if __name__ == "__main__":            sleep(2).addBoth(print_)            reactor.callLater(.1, running)            reactor.callLater(3, reactor.stop)            reactor.run()

Discussion:

How to make blocking code non-blocking is the obvious question for
everybody using Twisted, but the Twisted documentation does not make
easy to find the solution :-(

The trick is to run the blocking function in a separate thread. Here
all the magic is performed by the decorator, ``deferred``, which converts
``sleep``, a blocking function, into a deferred function i.e. a
non-blocking function that returns a deferred object. The code for
``callInThread`` is clear, and the ``.__get__`` trick converts
``callInThread`` in a one-argument function returning a closure,
i.e. an object suitable to be used as a decorator. I have seen this
trick in Alex Martelli‘s lectures at PyCon 2005. If you are confused
by it, you should read Raymond Hettinger essay on descriptors
(http://users.rcn.com/python/download/Descriptor.htm).

In short: every time you have a blocking function in your code, wrap
it with the ``deferred`` decorator and live happy!




本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Python Twisted介紹
在Twisted中使用線程(2)
twisted學(xué)習(xí)筆記之: 延遲對象deferred
Twisted:Python事件驅(qū)動的網(wǎng)絡(luò)引擎庫
如何更好更快的進行Python編寫?
Python開發(fā)一個簡單的聊天室
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服