我认为问题的措辞有点误导 - 实际上你想关闭你用os.startfile(file_name)打开的应用程序
不幸的是,os.startfile 没有为您提供返回进程的任何句柄。
help(os.startfile)
启动相关应用程序后,startfile 立即返回。
没有选项等待应用关闭,也没有办法
检索应用程序的退出状态。
幸运的是,您还有另一种通过 shell 打开文件的方法:
shell_process = subprocess.Popen([file_name],shell=True)
print(shell_process.pid)
返回的 pid 是父 shell 的 pid,而不是您的进程本身的 pid。
杀死它是不够的——它只会杀死一个 shell,而不是子进程。
我们需要找到孩子:
parent = psutil.Process(shell_process.pid)
children = parent.children(recursive=True)
print(children)
child_pid = children[0].pid
print(child_pid)
这是您要关闭的 pid。
现在我们可以终止进程了:
os.kill(child_pid, signal.SIGTERM)
# or
subprocess.check_output("Taskkill /PID %d /F" % child_pid)
请注意,这在 Windows 上有点复杂 - 没有 os.killpg
更多信息:How to terminate a python subprocess launched with shell=True
另外,当我尝试使用os.kill 终止 shell 进程时,我收到了PermissionError: [WinError 5] Access is denied
os.kill(shell_process.pid, signal.SIGTERM)
subprocess.check_output("Taskkill /PID %d /F" % child_pid) 为我工作了任何进程,没有权限错误
见WindowsError: [Error 5] Access is denied