Python:让 subprocess.Popen 启动的进程在退出后保持活动状态
Python: Keep processes started by subprocess.Popen alive after exiting
我正在制作一个可以使用 subprocess.Popen("path/to/app.exe")
启动多个程序的虚拟助手。但是当我退出 python 程序时,所有进程都被终止了。我希望进程(以 Popen 启动的应用程序)是独立的,并在主进程被终止后保持活动状态。
我已经尝试按照一些帖子的建议在 subprocess.Popen()
中添加 start_new_session=True
作为参数,但它仍然不起作用。
我认为没有必要显示代码,但是,给你。
app_path = r'C:\Users\myusername\AppData\Local\Discord\app-1.0.9001\discord.exe'
subprocess.Popen(app_path) # also tried adding start_new_session=True as argument
因为你在 Windows,你可以调用 start
命令,它的存在就是为了这个目的:运行 另一个独立于启动它的程序。
start
命令由command-line解释器提供cmd.exe
. It is not an executable: there is no start.exe
. It is a "shell command" (in Linux terminology), which is why shell=True
创建子进程时必须传递
您将无法与以这种方式启动的子进程通信,也就是说,不能通过 subprocess
module. So instead of Popen
, you may just use the convenience function run
:
提供的管道机制
from subprocess import run
app = 'notepad'
run(['start', app], shell=True)
该示例启动记事本编辑器(而不是问题中的 Discord)以使其更容易重现。
如果 app
的完整路径包含空格,我们可以像这样调用 start
app = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
run(f'start "" "{app}"', shell=True)
本例使用Edge浏览器,或单独传目录:
folder = r'C:\Program Files (x86)\Microsoft\Edge\Application'
app = 'msedge.exe'
run(['start', '/d', folder, app], shell=True)
这是必需的,因为 start
将单个参数视为 window 标题(如果该参数在引号中)。并且只有在没有的情况下,它才会将其视为命令。有关详细信息,请参阅 "Can I use the start
command with spaces in the path?"(在 SuperUser 上)。
我正在制作一个可以使用 subprocess.Popen("path/to/app.exe")
启动多个程序的虚拟助手。但是当我退出 python 程序时,所有进程都被终止了。我希望进程(以 Popen 启动的应用程序)是独立的,并在主进程被终止后保持活动状态。
我已经尝试按照一些帖子的建议在 subprocess.Popen()
中添加 start_new_session=True
作为参数,但它仍然不起作用。
我认为没有必要显示代码,但是,给你。
app_path = r'C:\Users\myusername\AppData\Local\Discord\app-1.0.9001\discord.exe'
subprocess.Popen(app_path) # also tried adding start_new_session=True as argument
因为你在 Windows,你可以调用 start
命令,它的存在就是为了这个目的:运行 另一个独立于启动它的程序。
start
命令由command-line解释器提供cmd.exe
. It is not an executable: there is no start.exe
. It is a "shell command" (in Linux terminology), which is why shell=True
创建子进程时必须传递
您将无法与以这种方式启动的子进程通信,也就是说,不能通过 subprocess
module. So instead of Popen
, you may just use the convenience function run
:
from subprocess import run
app = 'notepad'
run(['start', app], shell=True)
该示例启动记事本编辑器(而不是问题中的 Discord)以使其更容易重现。
如果 app
的完整路径包含空格,我们可以像这样调用 start
app = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
run(f'start "" "{app}"', shell=True)
本例使用Edge浏览器,或单独传目录:
folder = r'C:\Program Files (x86)\Microsoft\Edge\Application'
app = 'msedge.exe'
run(['start', '/d', folder, app], shell=True)
这是必需的,因为 start
将单个参数视为 window 标题(如果该参数在引号中)。并且只有在没有的情况下,它才会将其视为命令。有关详细信息,请参阅 "Can I use the start
command with spaces in the path?"(在 SuperUser 上)。