-1

I am trying to stop a script I wrote automatically but I can't find a way to stop the threads as well as the main code.

import time
import threading
import sys

def thread():
    while True:
        print('hi')
        time.sleep(2)
        
t1 = threading.Thread(target=thread)
t1.start()

print('using sys.exit() in 5...')
time.sleep(1)
print('4')
time.sleep(1)
print('3')
time.sleep(1)
print('2')
time.sleep(1)
print('1')
time.sleep(1)
sys.exit()

This is a dummy code^. I'm no expert in python and I only know the basics. Is there a way and if so, how? Thanks!

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
SpaceFlier
  • 41
  • 3

1 Answers1

0

You could use a global variable to stop your thread:

import threading 
import time 

def thread(): 
    while True: 
        print('thread running') 
        global stop_threads 
        if stop_threads: 
            break

stop_threads = False
t1 = threading.Thread(target=thread) 
t1.start() 
time.sleep(1) 
stop_threads = True
t1.join() 
print('thread killed') 

More ways to stop threads in your situation are found here.

Cloudkollektiv
  • 11,852
  • 3
  • 44
  • 71