Python - 从 Web 应用程序启动长时间运行的进程
我有一个 python Web 应用程序,需要启动一个长时间运行的进程。问题是我不希望它等待该过程完成。只需启动并完成即可。
我在 Windows XP 上运行,并且 Web 应用程序在 IIS 下运行(如果重要的话)。
到目前为止,我尝试过 popen 但似乎不起作用。它一直等到子进程完成。
I have a python web application that needs to launch a long running process. The catch is I don't want it to wait around for the process to finish. Just launch and finish.
I'm running on windows XP, and the web app is running under IIS (if that matters).
So far I tried popen but that didn't seem to work. It waited until the child process finished.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,我终于明白了!这似乎有效:
注意:我添加了 shell=True。否则,在子进程中调用 print 会出现错误“IOError:[Errno 9] 错误的文件描述符”
DETACHED_PROCESS
是 进程创建标志 传递到底层 WINAPI CreateProcess 函数。Ok, I finally figured this out! This seems to work:
Note: I added shell=True. Otherwise calling print in the child process gave me the error "IOError: [Errno 9] Bad file descriptor"
DETACHED_PROCESS
is a Process Creation Flag that is passed to the underlying WINAPI CreateProcess function.您可以将作业写入消息队列,而不是直接从 Web 应用程序启动进程。单独的服务从消息队列中读取并运行作业。看一下 Celery,一个用 Python 编写的分布式任务队列。
Instead of directly starting processes from your webapp, you could write jobs into a message queue. A separate service reads from the message queue and runs the jobs. Have a look at Celery, a Distributed Task Queue written in Python.
这几乎有效(从这里):
“完成”将立即打印。问题是上面的进程一直运行直到 long_run.py 返回,如果我关闭该进程,它会杀死 long_run.py 的进程。
当然有某种方法可以使进程完全独立于父进程。
This almost works (from here):
'done' will get printed right away. The problem is that the process above keeps running until long_run.py returns and if I close the process it kills long_run.py's process.
Surely there is some way to make a process completely independent of the parent process.
subprocess.Popen 就是这样做的。
subprocess.Popen does that.