一番単純な実装は一定時間でbreakすることですね。
これは5秒でタイムアウトします。
python
1import time
2
3def loop():
4 start_time = time.time()
5 while True:
6 if time.time() - start_time > 5:
7 break
8
9loop()
10print('タイムアウトしました')
外部ライブラリを使っていいならtimeout-decoratorをインストールしましょう。簡単で分かりやすいです。
python
1from timeout_decorator import timeout, TimeoutError
2
3@timeout(5)
4def loop():
5 while True:
6 pass
7
8try:
9 loop()
10except TimeoutError:
11 print('タイムアウトしました')
12