2015-12-21 92 views
0

我想将下面的代码的答案返回给变量,变量应该每5秒更改一次,因此我不能使用'return',因为它结束了该函数。如何在不结束Python函数的情况下返回变量变量?

例如:

from time import sleep 

def printit(): 
    cpt = 1 
    while True: 
     if cpt < 3: 
      number = ("images[" + str(cpt) + "].jpg") 
      return number #here is the return 
      sleep(5) 
      cpt+=1 
     else: 
      printit() 

answer = printit() 
print(answer) #only 1 answer is printed, then the function ends because of the 'return' 

什么是解决这一问题的解决方案?

变量答案应每5秒更换一次而不终止该功​​能。

+6

一种用于发电机的工作https://wiki.python.org/moin /发电机或关闭http://www.shutupandship.com/2012/01/python-closures-explained.html?m=1 – dylan7

回答

7

解决此问题的解决方案是什么?可变回答应该每5秒更换一次而不终止该功​​能。

这里有一个方法基于generator functions

from time import sleep 

def printit(): 
    cpt = 1 
    while True: 
     if cpt < 3: 
      number = ("images[" + str(cpt) + "].jpg") 
      yield number #here is the return 
      sleep(5) 
      cpt+=1 
     else: 
      for number in printit(): 
       yield number 


for number in printit(): 
    print number 

这将使进程中运行,直到for循环没有收到更多的价值。要缓慢停止它,您可以发送一个值到发电机:

gen = printit() 
for i, number in enumerate(gen): 
    print i, number 
    if i > 3: 
     try: 
      gen.send(True) 
     except StopIteration: 
      print "stopped" 

对于这项工作,修改yield声明如下:

(...) 
stop = yield number #here is the return 
if stop: 
    return 
(...) 

取决于你想要达到这可能是什么或可能无法提供足够的并发水平。如果您想了解更多关于基于生成器的协同程序的知识,这些非常有见识的论文和David Beazley的视频是一个特例。

0

如果你想要一个无限的数量,你应该使用itertools.count与发电机的功能,这将允许你简洁地编写代码:

from itertools import count 
from time import sleep 

def printit(): 
    cn = count(1) 
    for i in iter(cn.next, 0): 
     yield "images[{}].jpg".format(i) 
     sleep(5) 

for answer in printit(): 
    print(answer) 
相关问题