【问题标题】:python pause infinite loop for code outside loop to be executedpython暂停无限循环以执行循环外的代码
【发布时间】:2018-04-19 14:36:04
【问题描述】:

我想知道这是否可能。我想要一个无限的while循环,但仍然不会在while循环之外的其余代码在循环打开时继续运行。例如,在每次迭代后打破 while 循环的方法。我需要找到一种方法来执行第二个打印语句,而不会完全破坏 while 循环。

while True:
   print('i will loop forever')

print('this code will never be executed because of the while loop')

【问题讨论】:

  • 使用多线程,在python中有很多选项可以做到这一点。
  • 好像你想使用线程,阅读它们。

标签: python


【解决方案1】:

有很多方法可以实现这一点,例如线程。但是,看起来您可能希望串行循环一段时间,中断,然后继续。生成器擅长于此。

例如:

def some_loop():
  i=0
  while True:
    yield i
    i+=1

my_loop=some_loop()

#loop for a while
for i in range(20):
  print(next(my_loop))

#do other stuff
do_other_stuff()

#loop some more, picking up where we left off
for i in range(10):
  print(next(my_loop))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多