You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python启动EXE程序,使其在脚本终止后仍持续运行?

问题:寻找符合Python风格的独立启动EXE程序的方法

需求:启动EXE程序后,Python脚本终止时EXE仍能继续运行,且启动函数无需等待EXE程序终止或退出。
已尝试:subprocess.Popen、subprocess.run、subprocess.call,未达到预期效果。
环境:Windows 10 系统,Python 3.11 版本


编辑2:使用detach=True参数时的报错

执行以下代码时出现错误:

C:\WINDOWS\system32>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb  7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> _npd = r'C:\Windows\System32\notepad.exe'
>>> with open('d:\output.log', 'w') as outfile:
...     subprocess.Popen([_npd],
...         stdout=outfile,
...         stderr=outfile,
...         stdin=subprocess.DEVNULL,
...         detach=True
...     )
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: Popen.__init__() got an unexpected keyword argument 'detach'
>>>

疑问:这段代码哪里出错了?


编辑3:不同运行环境下的异常表现

测试代码如下:

import subprocess
import sys
def myStartAPP(cmd):
    return subprocess.Popen(
        cmd,
        creationflags=subprocess.DETACHED_PROCESS
        )


_npd = r'C:\Windows\System32\notepad.exe'
_file = r'mytext.txt'
_notepad = [_npd, _file]
_calc = [r'C:\Windows\System32\calc.exe']

print(sys.version)
p1 = myStartAPP(_notepad)
p2 = myStartAPP(_calc)
exit()

运行结果差异

  • 命令行(CLI)环境:两个应用程序(记事本和计算器)都能保持打开状态,符合预期。
  • VSCodium环境:仅calc.exe保持打开,notepad.exe会被关闭(无论哪个应用先启动),同时出现以下错误:

D:_Testing Ground> c: && cd "d:_Testing Ground" && cmd /C
""C:\ProgramFiles\Python311\python.exe"
c:\Users\nn.vscode-oss\extensions\ms-python.python-2023.4.0-universal\pythonFiles\lib\python\debugpy\adapter/../../debugpy\launcher
60245 -- "d:_Testing Ground\start-APP.py" "
3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)]
Exception ignored in: <function Popen.del at
0x000001ABFB823E20> Traceback (most recent call last):
File "C:\Program Files\Python311\Lib\subprocess.py", line 1128, in del
self._internal_poll(_deadstate=_maxsize)
File "C:\Program Files\Python311\Lib\subprocess.py", line 1530, in _internal_poll
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OSError: [WinError 6] The handle is invalid.

疑问:命令行和VSCodium中的Python版本完全一致,开始怀疑subprocess是否为正确的解决方案。


内容的提问来源于stack exchange,提问作者stack-emil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 02:57:13