脚本结束时不要终止Python子进程

9 投票
2 回答
5952 浏览
提问于 2025-04-18 15:59

我看到很多人问这个问题的反面,觉得很奇怪,因为我总是无法让我的子进程保持运行。那么,有没有办法调用subprocess.Popen,并确保它的进程在调用的Python脚本退出后仍然保持运行呢?

我的代码如下:

dname = os.path.dirname(os.path.abspath(__file__))
script = '{}/visualizerUI.py'.format(dname)
self.proc = subprocess.Popen(['python', script, str(width), str(height), str(pixelSize)], stdout=subprocess.PIPE)

这段代码可以正常打开进程,但当我关闭我的脚本(无论是因为脚本完成还是按下Ctrl+C)时,visualizerUI.py这个子进程也会关闭,但我希望它能保持打开状态。或者至少有这个选项。

我错过了什么呢?

2 个回答

2

stdout=subprocess.PIPE去掉,然后加上shell=True,这样就可以在一个可以分开的子shell里运行。

2

另一个选择是使用:

import os
os.system("start python %s %s %s %s" % (script, str(width), str(height), str(pixelSize)))

这样可以在一个新的进程中启动你的新Python脚本,并且会打开一个新的控制台。

补充一下:我刚看到你是在Mac上工作,所以我怀疑这个方法可能不适合你。

那这样怎么样:

import os
import platform

operating_system = platform.system().lower()
if "windows" in operating_system:
    exe_string = "start python"
elif "darwin" in operating_system:
    exe_string = "open python"
else:
    exe_string = "python"
os.system("%s %s %s %s %s" % (exe_string, script, str(width),
          str(height), str(pixelSize))))

撰写回答