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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2970045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:35:19  来源:igfitidea点击:

Python - Launch a Long Running Process from a Web App

pythonwindowswinapipopenlong-running-processes

提问by Greg

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.

我有一个需要启动一个长时间运行的进程的 python web 应用程序。问题是我不希望它等待过程完成。只需启动并完成即可。

I'm running on windows XP, and the web app is running under IIS (if that matters).

我在 Windows XP 上运行,而 Web 应用程序在 IIS 下运行(如果这很重要)。

So far I tried popen but that didn't seem to work. It waited until the child process finished.

到目前为止,我尝试过 popen 但这似乎不起作用。它一直等到子进程完成。

回答by Greg

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"

注意:我添加了 shell=True。否则在子进程中调用打印会给我错误“IOError: [Errno 9] Bad file descriptor”

DETACHED_PROCESSis a Process Creation Flagthat is passed to the underlying WINAPI CreateProcessfunction.

DETACHED_PROCESS是传递给底层 WINAPI CreateProcess函数的进程创建标志

回答by Daniel Hepper

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.

您可以将作业写入消息队列,而不是直接从您的 web 应用程序启动进程。单独的服务从消息队列中读取并运行作业。看看Celery,一个用 Python 编写的分布式任务队列。

回答by Greg

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.

'done' 会立即打印出来。问题是上面的进程一直运行直到 long_run.py 返回,如果我关闭进程它会杀死 long_run.py 的进程。

Surely there is some way to make a process completely independent of the parent process.

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

回答by Ofri Raviv