gpt4 book ai didi

python - CherryPy 等待稍后停止的额外线程结束

转载 作者:行者123 更新时间:2023-12-01 03:02:23 27 4
gpt4 key购买 nike

我正在构建一个使用 CherryPy 提供 REST API 的应用程序,以及另一个执行后台工作的线程(实际上,它从串行端口读取数据)。

import cherrypy
import threading

class main:
@cherrypy.expose
def index(self):
return "Hello World."

def run():
while running == True:
# read data from serial port and store in a variable

running = True
t = threading.Thread(target = run)
t.start()

if __name__ == '__main__':
cherrypy.quickstart(main())

running = False

api.pc_main()run 都工作正常。问题是,我使用 running bool 值来停止我的线程,但那段代码永远不会到达,因为当我按 Ctrl-C 时,CherryPy 会等待该线程完成。我实际上必须使用 kill -9 来停止该进程。

最佳答案

我通过将我的线程设置为 CherryPy 插件来修复它。我使用了在这里找到的代码:Why is CTRL-C not captured and signal_handler called?

from cherrypy.process.plugins import SimplePlugin

class myplugin(SimplePlugin):
running = False
thread = None

def __init__(self, bus):
SimplePlugin.__init__(self, bus)

def start(self):
print "Starting thread."
self.running = True
if not self.thread:
self.thread = threading.Thread(target = self.run)
self.thread.start()

def stop(self):
print "Stopping thread."
self.running = False

if self.thread:
self.thread.join()
self.thread = None


def run(self):
while self.running == True:
print "Thread runs."
time.sleep(1)

然后在主脚本中:

if __name__ == '__main__':
mythread(cherrypy.engine).subscribe()
cherrypy.quickstart(main())

关于python - CherryPy 等待稍后停止的额外线程结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43696901/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com