加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:21:15 所属栏目:Python 来源:网络整理
导读:我看了一下,但我似乎无法解决这个问题.我想在我的django应用程序的视图中执行python脚本.我已经在django管理命令中放置了我想要执行的代码,因此可以通过命令行python manage.py命令名来访问它.然后我尝试使用subprocess.Popen(“python manage.py command-na

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

但是,此命令可能需要一些时间才能执行,因此我希望视图继续并允许脚本在后台执行.单独使用subprocess.Popen似乎会导致视图挂起,直到脚本完成,所以我尝试使用一个线程(遵循another 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()

然后执行它:

t = SubprocessThread("python manage.py command-name")
t.setDaemon(True)
t.start()
t.join()

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

最佳答案
也许你应该使用celery

Celery is a task queue/job queue based
on distributed message passing. It is
focused on real-time operation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读