[英]Generator as Callback
I am looking for a way to get stuff from a callback into a generator, 我正在寻找一种方法,可以将回调中的内容添加到生成器中,
or the generator to inherit the callback. 或生成器继承回调。
When the callback is called, the generator should run, yield
ing the data. 调用回调时,生成器应运行,并yield
数据。
def my_callback(some_data):
my_generator.execute(some_data) # what to do?
def my_generator():
while True:
yield some_data # from my_callback
# main program
for x in my_generator:
print(x)
# This is pseudo python code.
While I normally would use a queue and a thread to run and get that callback, in this case I am running inside a python extension of an cli which calls my_callback(data)
. 虽然我通常会使用队列和线程来运行并获取该回调,但在这种情况下,我正在cli的python扩展内运行,该扩展名为my_callback(data)
。
As a result, I can't use threading , as python will only execute that callback. 结果,我不能使用threading ,因为python将只执行该回调。 Afterwards the C part of the cli will do stuff again, and python is not executed. 之后cli的C部分将再次执行操作,并且不执行python。
Edit : I could register a 'poll' function, which will get called periodically. 编辑 :我可以注册一个“投票”功能,该功能会定期调用。 Putting a wait in there give at least the thread-queue construction some time to execute. 在那里等待至少给线程队列构造一些执行时间。 But that feels to dirty for actual code. 但这对实际代码来说太脏了。
The callback can send data to a coroutine which can send it along again if needed. 回调可以将数据发送到协程,协程可以在需要时再次发送该协程。 Not sure if this is what you are looking for but your question made me think of coroutines. 不确定这是否是您要寻找的东西,但您的问题使我想到了协程。
def my_callback(some_data):
cr.send(some_data) # what to do?
def my_coroutine(target):
n = 0
while True:
data = (yield) # from my_callback
print 'my_callback sent: {}'.format(data)
target.send(data) # to my_printer
def my_printer(prefix):
while True:
s = (yield) # from my_coroutine
print prefix + s
mp = my_printer('\t\t\t')
mp.next() # advance to the first yield
cr = my_coroutine(mp)
cr.next() # advance to the first yield
my_callback('foo')
for n in xrange(3):
my_callback('foo' + str(n))
cr.close()
mp.close()
>>>
my_callback sent: foo
foo
my_callback sent: foo0
foo0
my_callback sent: foo1
foo1
my_callback sent: foo2
foo2
>>>
If the callback execution is asynchronous, I'm not sure what would happen if the coroutine wasn't back to the first yield
and the callback tries to send it something, it might throw a ValueError: generator already executing
exception. 如果回调执行是异步的,则我不确定如果协程未返回至第一个yield
并且回调尝试向其发送某些内容,那么可能会引发ValueError: generator already executing
异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.