How to terminate a script with Python threads

Asked

Viewed 993 times

-2

I am working with a project and need the user to have the option to terminate it at any time, the cleanest way to do this I have found so far was by the process manager terminating the python process:

inserir a descrição da imagem aqui

And this returns me the following message:

inserir a descrição da imagem aqui

Because it is something that was done via task manager I think maybe there is something that can be written at the command prompt via script to perform the same task.

Ps: I’ve done some research and found several ways to terminate a script but I’ve tried using exit(), sys.exit() and quit() but they don’t completely shut down the code because my code uses Threading.

Maybe the path I’m following isn’t the best one for the situation, so any help on how to shut down the code altogether will be welcome.

  • 1

    I recommend you edit the question and enter your code. If you yourself suspect that you are not doing it right, we need to see the code to know how you did it.

1 answer

1


You can use the main code to be your application’s menu and kill threads when needed, as in this simple example (Python 3):

import threading
import time

def start():
    t1 = Thread()
    t1.start()
    op = 0
    while op != -1:
        print("Digite -1 para parar :)")
        op = int(input())
    print("saiu")
    t1.stop()

class Thread(threading.Thread):

    def __init__(self):
        super(Thread, self).__init__()
        self.kill = threading.Event()

    def run(self):
        # Enquanto a thread não estiver 'morta'
        while not self.kill.is_set():
            print("Thread executando")
            time.sleep(1)

    def stop(self):
        # Mata a thread
        print("thread parando.")
        self.kill.set()

if __name__ == "__main__":
    start()

Thread will be executed while the attribute self.kill is not set, and you can implement a more complex function in the stop() to ensure that the thread shutdown does not cause any problems (such as in data manipulation, etc).

  • 1

    Augusto thank you very much, I will not have problems with data handling in this script so your example met me perfectly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.