【发布时间】:2017-09-19 14:44:13
【问题描述】:
我一直在测试多个选项都无济于事。
我有一个 Flask 应用程序正在运行,并允许用户在另一个正在运行的进程中启动和停止后台功能,直到被“停止”信号终止。
这是可行的,但是我面临的问题是子进程,尽管已被终止,但仍有一个 PID 和一个退出代码(0、-15、-9,取决于我尝试过的内容)。
因此,用户无法重新启动该函数,因为它会生成:
AssertionError : 你不能启动一个进程两次。
我需要重新启动 Flask 应用才能再次启动后台功能。下面是后台功能的代码:
class background_function(Process):
def __init__(self):
Process.__init__(self)
self.exit = Event()
def shutdown(self):
self.exit.set()
def run(self):
#some variables declared here, and a try/except to verify that the
#remote device is online (a pi zero, function is using the remote gpio)
while not self.exit.is_set():
#code
还有Flask路由,通过html页面上的按钮点击触发:
proc = background_function()
@app.route('/_run', methods=['GET'])
def run():
if proc.pid is None:
try:
proc.start()
sleep(2)
if proc.is_alive():
return('Active')
else:
proc.shutdown()
sleep(0.1)
return('FAILED')
except Exception as e:
print(e)
proc.shutdown()
else:
p = psutil.Process(proc.pid)
p.kill()
return ('DISABLED')
请注意,psutil 是我最后一次尝试,它给出的结果与使用 process.terminate() 或后台函数是单个函数而不是类时完全相同。我的想法已经用完了,因此欢迎任何帮助或建议。
【问题讨论】:
-
我认为你必须重新初始化进程。您在这里总是使用相同的流程:
Process.__init__(self)。我觉得这个应该放在run -
哈。谢谢......我已经阅读了文档和“每个进程最多只能调用一次”,但认为在终止进程后它将被“重置”。我很确定这是一个愚蠢的错误:@
-
好的,所以我重新测试并管理了它的工作。除了 M Dennis 的解决方案之外,我还必须在 Flask 路由的 def run() 中将 proc global
global proc重新声明为proc = background_function()。我还必须将super().__init__()添加到班级的def __init__(self)。
标签: python flask multiprocessing