Python - 从 Web 应用程序启动长时间运行的进程

发布于 2024-09-04 03:32:58 字数 170 浏览 9 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

﹎☆浅夏丿初晴 2024-09-11 03:32:58

好吧,我终于明白了!这似乎有效:

from subprocess import Popen
from win32process import DETACHED_PROCESS

pid = Popen(["C:\python24\python.exe", "long_run.py"],creationflags=DETACHED_PROCESS,shell=True).pid
print pid
print 'done' 
#I can now close the console or anything I want and long_run.py continues!

注意:我添加了 shell=True。否则,在子进程中调用 print 会出现错误“IOError:[Errno 9] 错误的文件描述符”

DETACHED_PROCESS进程创建标志 传递到底层 WINAPI CreateProcess 函数。

Ok, I finally figured this out! This seems to work:

from subprocess import Popen
from win32process import DETACHED_PROCESS

pid = Popen(["C:\python24\python.exe", "long_run.py"],creationflags=DETACHED_PROCESS,shell=True).pid
print pid
print 'done' 
#I can now close the console or anything I want and long_run.py continues!

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.

jJeQQOZ5 2024-09-11 03:32:58

您可以将作业写入消息队列,而不是直接从 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.

梦醒灬来后我 2024-09-11 03:32:58

这几乎有效(从这里):

from subprocess import Popen

pid = Popen(["C:\python24\python.exe", "long_run.py"]).pid
print pid
print 'done'

“完成”将立即打印。问题是上面的进程一直运行直到 long_run.py 返回,如果我关闭该进程,它会杀死 long_run.py 的进程。

当然有某种方法可以使进程完全独立于父进程。

This almost works (from here):

from subprocess import Popen

pid = Popen(["C:\python24\python.exe", "long_run.py"]).pid
print pid
print 'done'

'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.

ら栖息 2024-09-11 03:32:58

subprocess.Popen 就是这样做的。

subprocess.Popen does that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文