简体   繁体   English

Python子进程不会在后台继续运行

[英]Python subprocess does not continue running in the background

I want to run a shell script in background with the subprocess. 我想在子进程的后台运行shell脚本。 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. 为简单起见,我将sleep命令用作脚本。 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. 如果我设置了communication或wait方法,那么它将继续运行,但这不是我想要的。

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

Have you looked at what happens when you run your program? 您是否看过运行程序时会发生什么? Even though it seems like the program ends, the thread will contiune to execute to completion. 即使程序看起来已结束,线程也将继续执行直到完成。 In your current example, this is hard to see but looking at an example like 在您当前的示例中,这很难看,但是看一个类似

import threading

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

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

If you store this program as eg delayed_print.py and the runs python delayed_print.py from the command line, you will see that the program ends and control is returned to the shell, but then a few seconds later, the text delayes is suddenly appearing in the shell window. 如果将该程序存储为例如delayed_print.py并从命令行运行python delayed_print.py ,您将看到该程序结束并且控制权返回到Shell,但是几秒钟后,文本delayes突然出现在外壳窗口中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM