从外部停止循环的最佳方法是什么?

Rev*_*est 3 python loops break python-3.x

我有一个打印微调器的 python 脚本。希望这个旋转器将持续到停止。

spinnerFrames = [
    "/",
    "-",
    "\\",
    "|",
]

def spinner():
  i = 0
  while True:
    clearScreen() #function to clear the screen
    print(spinnerFrames[i])
    i = i + 1
    if (i == 3):
      i = 0
    sleep(0.15)

spinner()
sleep(3)
# break out here
print("Done!")
Run Code Online (Sandbox Code Playgroud)

我知道你可以做sys.stdout.write()然后只删除那条线,但这不是重点。

我想不出停止循环和退出函数的最佳方法。(继续我的代码)我希望能够在你调用它的地方打破循环,因为我希望把它变成一个 Pip 包。

我认为这是可能的,尽管我不知道该怎么做。谢谢你的帮助!

Lio*_*oft 6

您需要异步运行它,就像多处理库允许您这样做一样。当你创建一个单独的线程时,你会在它上面留下一个句柄,当你想要它停止时,你可以用它来杀死它。

from multiprocessing import Process
from time import sleep
spinnerFrames = [
    "/",
    "-",
    "\\",
    "|",
]
def spinner():
  i = 0
  while True:
    print(spinnerFrames[i], end='\r')
    i = i + 1
    if (i == 3):
      i = 0
    sleep(0.15)
    
if __name__ == '__main__':
  p = Process(target=spinner)
  p.start()
  sleep(3)
  p.terminate()
  print("Done!")
Run Code Online (Sandbox Code Playgroud)

  • @RevelCarlbergWest 这是与 python 异步的一个很好的起点 - https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb (2认同)