Python subprocess does not continue running in the background

时间:2018-02-03 11:14:14

标签: python subprocess

I want to run a shell script in background with the subprocess. However, I don't want to wait for it to complete. I want it to run in background and terminate after it finishes. For simplicity, I am using the sleep command as my script. But as soon as I run, it terminates. If I put the communicate or wait method, then it keeps running but this is not what I want.

def run():
    subprocess.Popen(["sleep", "25s"])

1 个答案:

答案 0 :(得分:0)

您是否看过运行程序时会发生什么?即使看起来程序结束,线程仍将继续执行完成。在您当前的示例中,这很难看,但是看一下像

这样的示例
import threading

def wait_print():
    time.sleep(5)
    print('delayed')

t = threading.Thread(target=wait_print)
t.start()

如果您将此程序存储为例如delayed_print.py和命令行中的运行python delayed_print.py,您将看到程序结束并且控件返回到shell,但几秒钟后,文本delayes突然出现在shell窗口中。