Python RuntimeError:对于初学者,线程只能启动一次

Python RuntimeError:对于初学者,线程只能启动一次,python,multithreading,python-3.x,Python,Multithreading,Python 3.x,这是我的第一个节目。我试图将此加载动画放入while循环中,但在第二个“f.start()”之后会出现此错误。因为我对线程了解不多,所以我在Google上找到的“帮助”根本没有帮助,它涉及到长代码和类创建以及所有事情。有人能帮我理解我在这里能做什么吗 我从这里复制了动画代码: 正如错误所说,一个线程只能启动一次。因此,创建一个新线程。还要注意,我使用join等待旧线程停止 import itertools import threading import time import sys #h

这是我的第一个节目。我试图将此加载动画放入while循环中,但在第二个“f.start()”之后会出现此错误。因为我对线程了解不多,所以我在Google上找到的“帮助”根本没有帮助,它涉及到长代码和类创建以及所有事情。有人能帮我理解我在这里能做什么吗

我从这里复制了动画代码:



正如错误所说,一个线程只能启动一次。因此,创建一个新线程。还要注意,我使用
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

非常感谢。还有一件事:你知道为什么这段代码一直在“处理”而从不停止吗?代码是一样的,我只是添加了参数来将“加载”和“完成!”文本更改为其他内容。是的
t=threading.Thread(目标=动画(“处理”,“处理完成!”)
。此代码在创建线程之前调用
动画(..)
。由于设置
done
的主代码不运行,因此它永远在主线程中运行,而后台线程永远不会启动。改为执行
t=threading.Thread(target=animate,args=(“处理”,“处理完成!”)
。线程将使用参数启动
动画。
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