2016-11-14 4 views
0

エラーが発生した場合は、スレッドの作業イベントを維持します。 (python2)Python、どのようにスレッドの作業を維持するには?

作業スレッド:私は、サーバーを閉じると

def thread_update(n): 
    """Send the data to server per n second.""" 
    while True: 
     update_data() # the function that posting data to server 
     time.sleep(n) 

thread_u = threading.Thread(name='thread_u', target=thread_update, args=(5,)) 
thread_u.start() 

、thread_uはエラーと終了が発生します:

Exception in thread thread_u 
... 
HTTPError: HTTP Error 502: Bad Gateway 

だから私は働いてそれを維持するためにデーモンスレッドを作成(thread_uが終了したら、もう一度起動したい)

デーモンスレッド:

def thread_daemon(n): 
    while True: 
     if not thread_u.isAlive(): 
      thread_u.run() 
     time.sleep(n) 

thread_d = threading.Thread(name='thread_d', target=thread_daemon, args(60)) 
thread_d.start() 

ここで問題は、デーモンが一度作業して同じエラーで終了することです。

Exception in thread thread_u 
... 
HTTPError: HTTP Error 502: Bad Gateway 


Exception in thread thread_d 
... 
HTTPError: HTTP Error 502: Bad Gateway 

エラーが発生した場合は、thread_d作業イベントをそのままにしておきます。または、エラーが発生した場合は、thread_u作業イベントをそのままにしておきます。

答えて

1

あなたの目標はあなたのスレッドの作業を続けるのであれば、単に内部の例外を処理そのrun

def thread_update(n): 
    while True: 
     try: 
      update_data() 
      time.sleep(n) 
     except Exception as error: 
      print(error) 
0

例外をキャッチできます。

try: 
    update_data() 
except HTTPError as e: 
    print(e,file=sys.stderr) 
0

thread_updateで例外をキャッチしてみませんか?

import logging 

def thread_update(n): 
    """Send the data to server per n second.""" 
    while True: 
     try: 
      update_data() # the function that posting data to server 
     except HTTPError: 
      logging.exception("meh") 
     time.sleep(n) 

thread_u = threading.Thread(name='thread_u', target=thread_update, args=(5,)) 
thread_u.start() 
関連する問題