将(收益率)分配给变量

Assigning (yield) to a variable

首先,我想说明一下,我对Python并不是特别熟悉。我最近被迫熟悉一个让我目瞪口呆的代码示例,但我无法 "translate" 它。我看过的各种文档和文章也没有帮助:

这是相关函数的简化版本:

@coroutine
def processMessage(receiver):
    global userID
    #...
    while True:
        msg = (yield)
        try:
            #...
        except Exception as err:
            #...

我无法理解它的作用,因此无法 "walk through" 代码。我的问题是 "What does this function do?" 和 "What sequences does this function follow?"

让我失望的是 msg = (yield)。我不知道它想要达到什么目的。直觉告诉我它只是在新消息通过时抓取新消息,但我不明白 为什么 。如果有人知道并且我提供了足够的信息,我将不胜感激。

Try 子句:

if msg['event'] == 'message' and 'text' in msg and msg['peer'] is not None:
    if msg['sender']['username'] == username:
        userID = msg['receiver']['peer_id']
        config.read(fullpath + '/cfg/' + str(userID) + '.cfg')
        if config.has_section(str(userID)):
            log('Config found')
            readConfig()
            log('Config loaded')
        else:
            log('Config not found')
            writeConfig()
            log('New config created')
    if 'username' in msg['sender']:
        parse_text(msg['text'], msg['sender']['username'], msg['id'])

P.S。 receiver 是套接字接收器。

生成器中的语法 variable = (yield some_value) 执行以下操作:

  • 它 returns some_value 到调用它的代码(通过 nextsend);
  • 下次调用时(通过 .next.send(another_value)),它会将 another_value 分配给 variable 并继续执行。

例如,假设您有一个生成器函数:

>>> def f():
...     while True:
...         given = (yield)
...         print("you sent me:", given)
...

现在,让我们打电话给f。 returns 我们是一台发电机。

>>> g = f()

我们第一次使用生成器时无法向其发送数据

>>> next(g)

此时它只是评估了 yield ...当我们现在调用 .send 时它将从那一点继续,将我们发送给它的数据分配给变量 given

>>> g.send("hello")
('you sent me:', 'hello')
>>> g.send("there")
('you sent me:', 'there')

在您的特定示例代码中,您有一个生成器:

  • 正在从外部收到一条要处理的消息...将调用 .send(some_msg)
  • 它将处理该消息,然后返回给外部调用者,后者将向其提供另一条消息。