python:在后台运行命令

3 投票
2 回答
2204 浏览
提问于 2025-04-17 06:02

我有一个比较复杂的报告生成工作,这个报告需要从多个表格中提取数据。最后的报告会生成在一个Excel表格里。这个过程大概需要10到20分钟。

我们为客户提供了一个Django的网页应用。唯一的问题是,当客户请求报告时,我们需要生成一个网址,这个过程比较耗时,对用户界面来说是个问题。

我希望这个任务能够在后台运行,等完成后再给客户发一封邮件,里面有报告的链接。请问应该采用什么样的策略,使用哪些库比较合适?

2 个回答

1

也许下面的程序对你有帮助。

background.py

import subprocess

def background_execute(command):
    # launching the command
    p1 = subprocess.Popen(command,shell=True,stdout=True)
    p1.wait()
    print "Wait over, child exits"
    <Here you can add code to send mail>

使用方法:

background_execute(["python sleep.py"])

sleep.py

import time

print "I am in sleep script, and will sleep for 10 sec"
time.sleep(10)
print "exit from child"
4

你可以使用http://celeryproject.org/,这个工具非常好用,跟Django结合得很好,文档也写得很清楚,很多人都在用。

撰写回答