python kill thread code example

Example 1: python kill script

import sys
sys.exit()

Example 2: python terminate thread

# You can do it the same way as ending any process
# Just get out of the loop with a break or have an if-statement that
# triggers the code to jump to the end ;)

Example 3: kill threading in python

import random
import threading
import time

def bg_thread():
    for i in range(1, 30):
        print(f'{i} of 30 iterations...')
        time.sleep(random.random())  # do some work...

    print(f'{i} iterations completed before exiting.')

th = threading.Thread(target=bg_thread)
th.start()
th.join()