如何在 python 子进程中 运行 而不阻塞 parent 进程?

How to run in python subprocess without blocking parent process?

我知道问题类似于:1, 2 但这些问题的答案并没有解决我的问题。

坚果中的工作流程shell:

1.Web 应用程序向后端发送请求。 (用 django 编写)

2.Backend 启动 worker 进程,通过调用来完成一些工作:

run_command = [sys.executable, my_python_worker, flags]
logger.debug('Created os update process "%s" ', run_command)
subprocess.Popen(run_command)

并在 return parent 进程中将 http 200 发送到 Web 应用程序:

logger.debug('Sending response http 200')
return Response(status=status.HTTP_200_OK)

3.Progress 的子流程工作由 Web 应用程序使用后端 api 监控。

问题:

Worker 作为单独的 python 脚本实现。对于 运行 worker 我使用了 python subprocess 库中的 Popen object。 子进程已成功启动,我可以在第二个 shell 控制台中观察到它的工作进度。后端 parent 进程的执行也在进行中。我能够看到日志 Sending response http 200 但对 Web 应用程序的响应 http 200 从未出现。 然而,在子进程结束的那一刻(因为它已经结束了它的工作,或者我从 shell 中杀死了它)缺少的 http 200 响应立即被网络应用程序接收到。

问题:

如标题所示,如何在 python 中 运行 子进程,使其不会阻止 parent 进程发送 http 响应?

阅读 subprocess 库的文档后,我找到了标志:close_fds。 根据文档:

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.

我在我的代码中更改了行:

subprocess.Popen(run_command)

至:

subprocess.Popen(run_command, close_fds=True)

它解决了问题。似乎子进程已经获取并阻塞了父进程使用的套接字。