Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
37 lines (34 loc) · 1 KB

File metadata and controls

37 lines (34 loc) · 1 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# SuperFastPython.com
# example of a thread closing itself via an exception
from random import random
from time import sleep
from threading import Thread
import threading
# handle exceptions in new thread
def handler(args):
print(f'Got: {args.exc_value}')
# custom function to be executed in a new thread
def task():
# loop forever
while True:
# generate a random value between 0 and 1
value = random()
print(f'.{value}')
# block
sleep(value)
# check if we should close the thread
if value > 0.9:
print('Closing thread')
raise Exception('Stop now!')
# protect the entry point
if __name__ == '__main__':
# register a handler for exception in a new thread
threading.excepthook = handler
# create and configure the new thread
thread = Thread(target=task)
# start the new thread
thread.start()
# wait for the thread to terminate
thread.join()
# main continues on
print('Main continuing on...')
Morty Proxy This is a proxified and sanitized view of the page, visit original site.