因此,在我的脚本中,我以无头方式运行可执行文件。但是当用户退出/关闭脚本时我需要关闭它。我尝试了这段代码,但它不起作用,run.exe 仍在后台运行。 (我使用进程黑客验证)
#....
# Close run.exe at exit
def clear(process):
subprocess.call(f"TASKKILL /F /IM {process}", shell=True)
#...
# Run no gui "run.exe" in headless
def run():
exe_path = "engine/run.exe"
startupinfo = None
if sys.platform == "win32":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(
exe_path,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
startupinfo=startupinfo,
creationflags=subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP,
close_fds=True,
shell=False,
)
atexit.register(clear, process)
(这对我来说不起作用)
Python 11.2、Windows (x64)
您遇到的问题是
subprocess.pOpen()
返回一个 pOpen
对象,而不仅仅是进程 ID。当我测试示例代码时,对 TASKKILL
的调用返回了错误消息:The syntax of the command is incorrect.
,因为没有传入 pid。
简单的解决方案是在某个时刻访问
process.pid
,无论是在调用 atexit.register(clear, process)
, 时
atexit.register(clear, process.pid)
或在
clear(process)
函数本身内
# Close run.exe at exit
def clear(process):
subprocess.call(f"TASKKILL /F /IM {process.pid}", shell=True)
另一个考虑因素是使用
os.kill
而不是使用子进程来调用 TaskKill。
import os
import signal
...
atexit.register(os.kill, process.pid, signal.SIGTERM)