如何在Python中运行另一个脚本而不等待它完成? [英] How do I run another script in Python without waiting for it to finish?

查看:755
本文介绍了如何在Python中运行另一个脚本而不等待它完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个允许他运行特定作业的用户创建一个小信息板。我正在使用Django,所以我希望他能够点击一个链接来开始这个工作,然后将页面返回给他,并显示该作业正在运行。这个工作的结果将会稍后通过电子邮件发送给他。

I am creating a little dashboard for a user that will allow him to run specific jobs. I am using Django so I want him to be able to click a link to start the job and then return the page back to him with a message that the job is running. The results of the job will be emailed to him later.

我相信我应该使用 subprocess.Popen 但我不确定。所以在伪代码中,这里是我想做的:

I believe I am supposed to use subprocess.Popen but I'm not sure of that. So in pseudocode, here is what I want to do:

if job == 1:
    run script in background: /path/to/script.py
    return 'Job is running'


推荐答案

p = subprocess.Popen([sys.executable, '/path/to/script.py'], 
                                    stdout=subprocess.PIPE, 
                                    stderr=subprocess.STDOUT)

这将在后台启动子进程。您的脚本将保持正常运行。

That will start the subprocess in background. Your script will keep running normally.

阅读文档 here

这篇关于如何在Python中运行另一个脚本而不等待它完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆