仕事のさまざまな側面をテストするために使用する Python GUI があります。現在、各テストの最後にプロセスを強制終了する「停止」ボタンがあります(一度に実行するように複数のテストを設定できます)。ただし、一部のテストは実行に時間がかかり、テストを停止する必要がある場合はすぐに停止したいと考えています。私の考えは使用することです
import pdb; pdb.set_trace()
exit
しかし、これを次の実行コード行に挿入する方法がわかりません。これは可能ですか?
スレッドの場合は、下位レベルthread
(または_thread
Python 3)モジュールを使用して、を呼び出すことで例外を除いてスレッドを強制終了できthread.exit()
ます。
ドキュメントから:
よりクリーンなメソッド(処理の設定方法によって異なります)は、インスタンス変数を使用して処理を停止して終了するようにスレッドに通知しjoin()
、メインスレッドからメソッドを呼び出してスレッドが終了するまで待機することです。
例:
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self._stop_req = False
def run(self):
while not self._stop_req:
pass
# processing
# clean up before exiting
def stop(self):
# triggers the threading event
self._stop_req = True;
def main():
# set up the processing thread
processing_thread = MyThread()
processing_thread.start()
# do other things
# stop the thread and wait for it to exit
processing_thread.stop()
processing_thread.join()
if __name__ == "__main__":
main()