Python 线程启动/停止



我正在尝试在我的代码中实现一个启动/停止函数。

为简单起见,让我们假设我有两个函数:

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退出,但 actual_process(( 的 while 循环继续运行而不会停止。但是,它会启动 setup((。但是由于 actual_process(( 没有停止,我无法重置参数。

所以我的问题是,如何更改 while 循环停止的代码?

我做了一些更改:

  • 正如 Nearoo 所说,您有 2 个不同的变量名称continue_processcontinue_processinging
  • 我在setup()中添加了一个对actual_process()的调用
  • 您忘记了input(...)行中'引号
  • 我在它停止时添加了一个break语句,因此没有另一个不需要的循环

你可以试试这个:

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(),全局 while 循环while start_process:将自动执行此操作。

我还添加了一个example_of_process(),用于递增 varcount并打印它,只是为了模拟我们可以重新启动或停止的无限过程。

请注意,您需要按"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()

最新更新