python 扭曲 : "wait" for a variable to be filled by another event

标签 python asynchronous twisted

我知道 twisted 不会“等待”...我正在使用 XMPP 客户端与外部进程交换数据。我发送了一个请求,需要获取相应的答案。我使用 sendMessage 将我的请求发送到服务器。当服务器应答时,onMessage 方法将接收它并检查它是否是对请求的应答(不一定是我正在寻找的应答)并将任何应答放入堆栈中。 作为返回到我的 sendRequest 我想返回结果,所以我想从堆栈中弹出对我的请求的响应并返回。 我阅读了有关线程、延迟、回调和条件的信息,尝试了很多示例,但没有一个对我有用。所以我这里的示例代码是非常精简的伪代码来说明我的问题。任何建议表示赞赏。

class Foo(FooMessageProtocol):
    def __init__(self, *args, **kwargs):
        self.response_stack = dict()
        super(Foo, self).__init__(*args, **kwargs)    


    def sendRequest(self, data):
        self.sendMessage(id, data)
        # I know that this doesn't work, just to illustrate what I would like to do:
        while 1: 
            if self.response_stack.has_key(id):
               break
               return self.response_stack.pop(id) 


    def receiveAnswers(self, msg):
        response = parse(msg)
        self.response_stack[response['id']] = response

最佳答案

不能将结果返回给sendRequest,因为sendRequest等不及。 让 sendRequest 返回一个 Deferred,并在结果到达时触发它。

所以调用 sendRequest 的代码可以只向 deferred 添加一个回调,当有响应时它就会被调用。

像这样的东西(伪代码):

class Foo(FooMessageProtocol):
    def __init__(self, *args, **kwargs):
        self._deferreds = {}
        super(Foo, self).__init__(*args, **kwargs)    

    def sendRequest(self, data):
        self.sendMessage(id, data)
        d = self._deferreds[id] = defer.Deferred()
        return d

    def receiveAnswers(self, msg):
        response = parse(msg)
        id = response['id']
        if id in self._deferreds:
            self._deferreds.pop(id).callback(response)

关于 python 扭曲 : "wait" for a variable to be filled by another event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636890/

相关文章:

python - 自定义损失函数结果与内置损失函数结果不匹配

java - Java异步HttpClient请求似乎阻塞了主线程?

javascript - 可以在 NodeJS/Javascript 中使用 while/for 循环将此递归代码编写为迭代代码吗

python - Airflow 用户创建

python - 我们可以下载 python 的 urllib2 库吗?

Python:扭曲的服务器和值(value)观

python - 使用 Twisted 子进程和 virtualenvwrapper 时如何导入模块?

python - 检测客户端连接到哪个端口

python - 在 Dict 类型变量中使用字符串变量

.net - 新的异步方法和性能