python начало / остановка резьбы - PullRequest
0 голосов
/ 04 февраля 2020

Я пытаюсь реализовать функцию запуска / остановки в моем коде.

Для простоты предположим, что у меня есть две функции:

def setup():
    global start_process
    # setting up some parameters with user inputs
    actual_process()

def actual_process():
    global start_process, continue_process
    start_process = True
    while start_process:

        continue_process = True

        thread_1 = threading.Thread(target=start_stop)
        thread_1.daemon = True 
        thread_1.start()

        # do something infinitely


def start_stop():
    global continue_process, start_process
    while continue_process:
        user_input = input('Press "r" to restart or "s" to stop: ')
        if user_input == 's':
            continue_process = False
            start_process = False
            print('closing program')

        if user_input == 'r':
            continue_process = False
            start_process = False
            print('Restarting')
            setup()

setup()

Но когда я ввожу 's' или ' r 'функция start_stop закрывается, но пока l oop actual_process () продолжает работать без остановки. Однако он запускает setup (). Но так как actual_process () не останавливается, я не могу сбросить параметры.

Так что мой вопрос будет таким: как я могу изменить свой код, когда l oop останавливается?

1 Ответ

0 голосов
/ 04 февраля 2020

Я сделал несколько изменений:

  • , как сказал Nearoo, у вас было 2 разных имени переменных continue_process и continue_processing с ing
  • Я добавил вызов actual_process() в setup()
  • вы забыли кавычки ' в вашей input(...) строке
  • Я добавил оператор break, когда он останавливается , поэтому нет другого нежелательного l oop

Вы можете попробовать это:

import threading

def setup():
    global start_process, count
    count = 0
    # setting up some parameters with user inputs
    # and call actual_process()
    actual_process()

def actual_process():
    global start_process, continue_processing, count
    start_process = True
    while start_process:

        continue_processing = True

        thread_1 = threading.Thread(target=start_stop)
        thread_1.daemon = True 
        thread_1.start()

        # do something infinitely

def start_stop():
    global continue_processing, start_process
    while continue_processing:
        user_input = input('Press "r" to restart or "s" to stop:')
        if user_input == 's':
            continue_processing = False
            start_process = False
            print('closing program')
            break

        if user_input == 'r':
            continue_processing = False
            start_process = False
            print('Restarting')
            setup()

setup()

РЕДАКТИРОВАТЬ Теперь я не вызываю setup() при перезапуске, глобальное время l oop while start_process: сделает это автоматически.

Я также добавил example_of_process(), который увеличивает переменную count и печатает ее, просто для симуляции бесконечного процесса, который мы можем перезапустить или останов.

Обратите внимание, что вам нужно нажать «r + Enter» для перезапуска и «s + Enter» для остановки.

import threading
import time

def setup():
    global start_process 
    actual_process()

def actual_process():
    global start_process , continue_process, count
    start_process  = True
    count = 0
    while start_process :
        continue_process = True

        thread_1 = threading.Thread(target=start_stop)
        thread_1.daemon = True
        thread_1.start()

        example_of_process() # do something infinitely

def start_stop():
    global continue_process, start_process , count
    while continue_process:
        user_input = input('Press "r" + Enter to restart or "s" + Enter to stop: \n')
        if user_input == 's':
            continue_process = False
            start_process  = False
            print("closing program")
        if user_input == 'r':
            continue_process = False
            count = 0
            print("Restarting")

def example_of_process():
    global continue_process, count
    while continue_process:
        print("count", count)
        count += 1
        time.sleep(1)

setup()
...