Reputation: 149
This is for my first program. I am trying to put this loading animation in a while loop, but it gives this error after the second "f.start()". As I don't understand much about threads, the "help" I could find on Google was not helpful at all, which involved long codes with class creation and everything. Can somebody help me understand what I could do here?
I copied the animation code from here: 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
Upvotes: 1
Views: 6781
Reputation: 77347
As the error says, a thread can only be started once. So, create a new thread instead. Notice also that I use join
to wait for the old thread to stop.
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
Upvotes: 1