2017-01-13 7 views
0

これは私の最初のプログラムです。この読み込みアニメーションをwhileループに入れようとしていますが、2番目の "f.start()"の後にこのエラーが発生します。私はスレッドについて多くのことを理解していないので、私がGoogleで見つけた "ヘルプ"は役に立たず、クラス作成などの長いコードが含まれていました。誰かが私がここで何ができるのか理解するのを助けることができますか?RuntimeError:スレッドは初心者向けに一度だけ起動できます

私はここからアニメーションのコードをコピー:エラーが言うように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 

答えて

2

を、スレッドが一度だけ起動することができます。だから、代わりに新しいスレッドを作成してください。また、古いスレッドが停止するのを待つために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 
+0

ありがとうございます!もう一つのこと:このコードがなぜ止まることなく "処理"を続けるのかを知っていますか?コードは同じですが、「読み込み」と「完了」を変更するパラメータを追加しました。テキストを他のものに変換する。 https://gist.github.com/Setti7/e56284b59da6946af0b9924a0b9962aa – Setti7

+0

はい... 't = threading.Thread(target = animate(" Processing "、" Processing Complete! "))'。このコードは、スレッドを作成する前に 'animate(..)'を呼び出します。 'done'を設定するメインコードは実行されないので、メインスレッドで永久に実行され、バックグラウンドスレッドは決して起動しません。 't = threading.Thread(target = animate、args =(" Processing "、" Processing Complete! "))'を実行してください。スレッドは引数で 'animate'を開始します。 – tdelaney

関連する問題