在django视图中使用subprocess.Popen()执行python脚本

Ano*_*non 5 python django multithreading subprocess

我看了一下,但我似乎无法解决这个问题.我想在我的django应用程序的视图中执行python脚本.我已经在django管理命令中放置了我想要执行的代码,因此可以通过命令行访问它python manage.py command-name.然后我尝试使用运行此命令subprocess.Popen("python manage.py command-name",shell=True).

但是,此命令可能需要一些时间才能执行,因此我希望视图继续并允许脚本在后台执行.单独使用subprocess.Popen似乎会导致视图挂起,直到脚本完成,所以我尝试使用一个线程(跟随另一个 SA问题):

class SubprocessThread(threading.Thread):
def __init__(self, c):
    self.command = c
    self.stdout = None
    self.stderr = None
    threading.Thread.__init__(self)

def run(self):
    p = subprocess.Popen(self.command,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)

    self.stdout, self.stderr = p.communicate()
Run Code Online (Sandbox Code Playgroud)

然后执行它:

t = SubprocessThread("python manage.py command-name")
t.setDaemon(True)
t.start()
t.join()
Run Code Online (Sandbox Code Playgroud)

但是,视图仍然挂起:光标有一个忙符号,页面上的AJAX没有加载.否则,在线程调用看起来正常完成(脚本完成之前)后,页面的html似乎加载正常并且视图中的命令.有人可以帮帮我吗?我希望脚本能够在不阻止页面上的视图或AJAX调用的情况下执行并执行自己的操作.

Ald*_*und 4

也许你应该用芹菜

Celery是一个基于分布式消息传递的任务队列/作业队列。它注重实时操作