gpt4 book ai didi

python - 运行时错误: threads can only be started once for a beginner

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:25 26 4
gpt4 key购买 nike

这是我的第一个程序。我试图将此加载动画放入 while 循环中,但它在第二个“f.start()”之后给出此错误。由于我对线程不太了解,所以我在 Google 上找到的“帮助”根本没有帮助,其中涉及类创建和所有内容的长代码。有人可以帮助我了解我可以在这里做什么吗?

我从这里复制了动画代码:Python how to make simple animated loading while process is running

<小时/>
import itertools
import threading
import time
import sys


#here is the animation
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
if done:
break
sys.stdout.write('\rloading ' + c)
sys.stdout.flush()
time.sleep(0.25)
sys.stdout.write('\rDone! ')

t = threading.Thread(target=animate)

while True:
done = False
user_input = input('Press "E" to exit.\n Press"S" to stay.')
if user_input is "E":
break
elif user_input is "S":
# Long process here
t.start()
time.sleep(5)
done = True
time.sleep(1)
print("\nThis will crash in 3 seconds!")
time.sleep(3)
break


# Another long process here
t.start()
time.sleep(5)
done = True

最佳答案

正如错误所示,一个线程只能启动一次。因此,请创建一个新线程。另请注意,我使用 join 来等待旧线程停止。

import itertools
import threading
import time
import sys


#here is the animation
def animate():
for c in itertools.cycle(['|', '/', '-', '\\']):
if done:
break
sys.stdout.write('\rloading ' + c)
sys.stdout.flush()
time.sleep(0.25)
sys.stdout.write('\rDone! ')

t = threading.Thread(target=animate)

while True:
done = False
user_input = input('Press "E" to exit.\n Press"S" to stay.')
if user_input is "E":
break
elif user_input is "S":
# Long process here
t.start()
time.sleep(5)
done = True
t.join()
print("\nThis will crash in 3 seconds!")
time.sleep(3)
break


# Another long process here
done = False
t = threading.Thread(target=animate)
t.start()
time.sleep(5)
done = True

关于python - 运行时错误: threads can only be started once for a beginner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41626745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com