In my main python file that controls the program, I have a function that creates a thread for a function that has been passed in as a parameter.
def NewThread(com, Returning: bool, thread_ID, *arguments) -> Any:
"""
Will create a new thread for a function/command.
:param com: Command to be Executed
:param Returning: True/False Will the command return anything?
:param thread_ID: Name of thread created
:param arguments: Arguments to be sent to Command that is started in a thread
"""
class NewThreadWorker(Thread):
def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, *,
daemon = None):
Thread.__init__(self, group, target, name, args, kwargs, daemon = daemon)
self.daemon = True
self._return = None
def run(self):
if self._target is not None:
self._return = self._target(*self._args, **self._kwargs)
def join(self):
Thread.join(self)
return self._return
ntw = NewThreadWorker(target = com, name = thread_ID, args = (*arguments,))
if Returning:
ntw.start()
return ntw.join()
else:
ntw.start()
This function works and is great, however I have no way of interacting with the new thread that has been created. Usuallly, all you would have to do stop the thread is (in this case) ntw.join() however I have no way of doing this with my current setup. So after many trials and errors (many, many errors) I thought: Why can't I just assign the thread to a new variable and use .join() on that?
So, that now brings me to my question:
how can you kill a thread in python3 when you do not have access to the variable that started the thread (ntw
in this case)?
also if it is possible I would like keep the setup of NewThread function. (I don't really want to have manage each thread manually for every function I have, that would be very painful) Any help is greatly appreciated.
If you want to check out where the source code is for the project that this is integrated with, here is the github repo: https://github.com/vipersniper0501/CP_Scripts2/blob/dev/GUIs/ScriptRunnerPyQt5_GUI/ScriptGUIrunner.py
EDIT: I have looked Is there any way to kill a Thread? and this does not answer my question.