twsited中的同步代码使用

# -*- coding: utf-8 -*-
# @时间 : 2020/4/19 1:48 下午
# @作者 : 陈祥安
# @文件名 : inlinecallback_demo.py
# @公众号: Python学习开发
from twisted.internet.defer import inlineCallbacks, Deferred, returnValue, ensureDeferred
from twisted.python.failure import Failure

from twisted.internet import reactor, defer


def load_remote_data(callback):
    print("in load_remote_data")
    import time
    time.sleep(1)
    callback(1)


def load_remote_data2(callback):
    import time
    time.sleep(1)
    print("in load_remote_data2")
    callback(2)


@defer.inlineCallbacks
def get_remote_data():
    d1 = defer.Deferred()
    reactor.callInThread(load_remote_data, d1.callback)
    r1 = yield d1
    print("r1", r1)

    d2 = defer.Deferred()
    reactor.callInThread(load_remote_data2, d2.callback)
    r2 = yield d2
    print("r2", r2)

    return r1 + r2


def get_result(v):
    print("result=", v)


if __name__ == '__main__':
    d =get_remote_data()
    d.addCallback(get_result)

    reactor.callLater(3, reactor.stop)
    reactor.run()

python3.5以后上面的代码可以改为async/await的形式

# -*- coding: utf-8 -*-
# @时间 : 2020/4/19 1:48 下午
# @作者 : 陈祥安
# @文件名 : inlinecallback_demo.py
# @公众号: Python学习开发
from twisted.internet.defer import inlineCallbacks, Deferred, returnValue, ensureDeferred
from twisted.python.failure import Failure

from twisted.internet import reactor, defer


def load_remote_data(callback):
    print("in load_remote_data")
    import time
    time.sleep(1)
    callback(1)


def load_remote_data2(callback):
    import time
    time.sleep(1)
    print("in load_remote_data2")
    callback(2)


# @defer.inlineCallbacks
async def get_remote_data():
    d1 = defer.Deferred()
    reactor.callInThread(load_remote_data, d1.callback)
    r1 = await d1
    print("r1", r1)

    d2 = defer.Deferred()
    reactor.callInThread(load_remote_data2, d2.callback)
    r2 = await d2
    print("r2", r2)

    return r1 + r2


def get_result(v):
    print("result=", v)


if __name__ == '__main__':
    #将协程包装成defer对象
    d = ensureDeferred(get_remote_data())
    d.addCallback(get_result)

    reactor.callLater(3, reactor.stop)
    reactor.run()

上一篇:Go 面试每天一篇(第 1 天)


下一篇:go defer看到你头晕的操作