如何将生成器转换为仅返回由生成器生成的第一个值的函数?

时间:2017-02-15 02:17:20

标签: python function generator yield

我有一些代码打印出它在循环中收到的任何消息:

import pytg
import pytg.utils
import pytg.receiver

@pytg.utils.coroutine
def receiver_function(tg_receiver):
    while True:
        message = (yield)
        print(message)

tg_receiver = pytg.receiver.Receiver()
tg_receiver.start()
tg_receiver.message(receiver_function(tg_receiver))
receiver.stop()

我想更改此代码,以便它使用一个简单的函数,该函数会在遇到消息之前暂停,然后返回该消息,当然还有控制:

import pytg
import pytg.receiver

def get_one_message():
    tg_receiver.start()
    while #<insert magic>:
        #<insert magic>
        message = #<insert magic>
    tg.receiver.stop()
    return message

print(get_one_message())

怎么可以这样做?

1 个答案:

答案 0 :(得分:1)

pytg的Receiver.message doesn’t seem to give you access to the generator’s GeneratorExit,所以你可能不得不破解它:

def get_one_message():
    message = None

    @pytg.utils.coroutine
    def receiver_function(tg_receiver):
        nonlocal message
        message = (yield)

    tg_receiver.start()
    tg_receiver.message(receiver_function(tg_receiver))
    tg_receiver.stop()
    return message

或者潜入其未记录的(因此不稳定的)部分,尽管这样做不是一个好主意:

def get_one_message():
    tg_receiver.start()
    tg_receiver._new_messages.acquire()
    with tg_receiver._queue_access:
        message = tg_receiver._queue.popleft()
    tg_receiver.stop()
    return message