RuntimeError:只能为初学者启动一次线程

时间:2017-01-13 03:01:39

标签: python multithreading python-3.x

这是我的第一个节目。我试图将这个加载动画放在while循环中,但它在第二个" f.start()"之后给出了这个错误。由于我不太了解线程,所以"帮助"我在谷歌上找到的根本没有帮助,它涉及长码和类创作等等。有人可以帮我理解我能在这做什么吗?

我从这里复制了动画代码: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

1 个答案:

答案 0 :(得分:1)

如错误所示,线程只能启动一次。所以,改为创建一个新线程。另请注意,我使用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