- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson07_exception.py
More file actions
Latest commit
37 lines (34 loc) · 1 KB
/
Copy pathlesson07_exception.py
File metadata and controls
37 lines (34 loc) · 1 KB
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
fromrandomimportrandom
fromtimeimportsleep
fromthreadingimportThread
importthreading
# handle exceptions in new thread
defhandler(args):
print(f'Got: {args.exc_value}')
# custom function to be executed in a new thread
deftask():
# loop forever
whileTrue:
# generate a random value between 0 and 1
value=random()
print(f'.{value}')
# block
sleep(value)
# check if we should close the thread
ifvalue>0.9:
print('Closing thread')
raiseException('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...')