Код: Выделить всё
import time
import multiprocessing
import os
import signal
import logging
# Global variables to manage the training state
is_training = False
training_process = None
training_pid = None # Store the PID of the training process
stop_event = None
logger = logging.getLogger()
def train_task(stop_event):
"""simulates the training task with stop event support"""
for i in range(30):
if stop_event.is_set():
print("Training cancelled.")
return
time.sleep(1)
print("Training done.")
def train_model():
global is_training, training_process, stop_event
# If training is already in progress, return immediately
if is_training:
print("Training already in progress...")
return "Training already in progress"
#mark the start of the training
is_training = True
stop_event = multiprocessing.Event() #creates a stop event
print("Training started...")
#start the training process with stop event support
training_process = multiprocessing.Process(target = train_task, args=(stop_event,))
training_process.start()
#stores the pid of the process
training_pid = training_process.pid
return "Training started."
def cancel_training_process():
global training_pid, is_training, stop_event
if is_training and training_pid:
try:
os.kill(training_pid, signal.SIGTERM) #sends the SIGTERM signal to the process
is_training = False #resets the training state
training_pid = None
stop_event.set() # stops the training event
return "Training cancelled."
except OSError as e:
return f"Error while cancelling the process: {e}"
return "No training in progress"
def check_training_status():
global is_training
if is_training:
return "Training in progress"
else:
return "No training in progress"
Какой совет по этому поводу? В будущем обучение будет представлять собой совершенно другой сценарий, который будет получать данные из базы данных и обучать ИИ, но такой сценарий еще не написан, это просто я пытаюсь реализовать то, что меня попросили сделать хе-хе-хе< /p>
Я пробовал разные решения, ни одно из них не работает, когда я хочу отменить процесс, он все равно выполняется до конца, я уверен, что решение может быть, но это определенно пока мне неизвестно
Подробнее здесь: https://stackoverflow.com/questions/789 ... -in-django