Python 生成器预取?
我有一个生成器,每次迭代都需要很长时间才能运行。是否有一种标准方法让它产生一个值,然后在等待再次调用时生成下一个值?
每次在 GUI 中按下按钮时都会调用生成器,并且用户将在每次按下按钮后考虑结果。
编辑:解决方法可能是:
def initialize():
res = next.gen()
def btn_callback()
display(res)
res = next.gen()
if not res:
return
I have a generator that takes a long time for each iteration to run. Is there a standard way to have it yield a value, then generate the next value while waiting to be called again?
The generator would be called each time a button is pressed in a gui and the user would be expected to consider the result after each button press.
EDIT: a workaround might be:
def initialize():
res = next.gen()
def btn_callback()
display(res)
res = next.gen()
if not res:
return
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我想做像你的解决方法这样的事情,我会编写一个这样的类:
它比你的版本更复杂,因为我这样做是为了让它处理不调用预取或调用预取太多次的情况。基本思想是当您想要下一个项目时调用 .next() 。当你有“时间”可以消磨时,你可以调用预取。
您的另一个选择是线程。
这将与您的主应用程序分开运行。无论获取每次迭代需要多长时间,您的 GUI 都应该保持响应。
If I wanted to do something like your workaround, I'd write a class like this:
It is more complicated than your version, because I made it so that it handles not calling prefetch or calling prefetch too many times. The basic idea is that you call .next() when you want the next item. You call prefetch when you have "time" to kill.
Your other option is a thread..
This will run separately from your main application. Your GUI should remain responsive no matter how long it takes to fetch each iteration.
不。生成器不是异步的。这不是多处理。
如果您想避免等待计算,您应该使用
multiprocessing
包,以便独立的进程可以完成昂贵的计算。您需要一个单独的过程来计算和排队结果。
然后,您的“生成器”可以简单地将可用结果出列。
No. A generator is not asynchronous. This isn't multiprocessing.
If you want to avoid waiting for the calculation, you should use the
multiprocessing
package so that an independent process can do your expensive calculation.You want a separate process which is calculating and enqueueing results.
Your "generator" can then simply dequeue the available results.
您绝对可以使用生成器来做到这一点,只需创建生成器,以便每个
next
调用在获取下一个值和通过放入多个yield
语句返回它之间交替。下面是一个示例:请注意,生成器不会自动执行获取下一个值的处理,而是由调用者为每个值调用
next
两次。对于您的用例,您将调用next
一次作为设置,然后每次用户单击按钮时,您将显示生成的下一个值,然后再次调用next
预取。You can definitely do this with generators, just create your generator so that each
next
call alternates between getting the next value and returning it by putting in multipleyield
statements. Here is an example:Note that the generator does not automatically do the processing to get the next value, it is up to the caller to call
next
twice for each value. For your use case you would callnext
once as a setup up, and then each time the user clicks the button you would display the next value generated, then callnext
again for the pre-fetch.我在追求类似的东西。我希望当后台线程处理下一个时,yield 能够快速返回一个值(如果可以的话)。
上面的代码给出了以下结果:
I was after something similar. I wanted yield to quickly return a value (if it could) while a background thread processed the next, next.
The code above gave the following results: