【发布时间】:2018-09-06 13:18:27
【问题描述】:
我必须创建一个在内部调用中做一些艰苦工作的函数。这个函数需要是一个生成器,因为我使用的是服务器发送事件。所以,我希望这个函数通过使用“产量”来通知计算的进度。之后,该函数必须将结果传递给父函数才能继续进行其他计算。
我想要这样的东西:
def hardWork():
for i in range(N):
# hard work
yield 'Work done: ' + str(i)
# Here is the problem: I can't return a result if I use a yield
return result
def generator():
# do some calculations
result = hardWork()
# do other calculations with this result
yield finalResult
我找到了一个解决方案,该解决方案包括产生一个字典,告诉函数是否已完成,但执行此操作的代码非常脏。
还有其他解决方案吗?
谢谢!
编辑
我的想法是这样的:
def innerFunction(gen):
calc = 1
for iteration in range(10):
for i in range(50000):
calc *= random.randint(0, 10)
gen.send(iteration)
yield calc
def calcFunction(gen):
gen2 = innerFunction(gen)
r = next(gen2)
gen.send("END: " + str(r + 1))
gen.send(None)
def notifier():
while True:
x = yield
if x is None:
return
yield "Iteration " + x
def generator():
noti = notifier()
calcFunction(noti)
yield from noti
for g in generator():
print(g)
但我收到此错误:
TypeError: can't send non-None value to a just-started generator
【问题讨论】:
-
我认为你应该真正阅读异步函数,因为这与你正在做的非常接近
标签: python generator yield server-sent-events