【问题标题】:How to close all opened windows from python?如何从python关闭所有打开的窗口?
【发布时间】:2021-01-07 06:30:17
【问题描述】:

我正在用 python 制作个人语音助手。在我的程序中,我编写了一个可以关闭我的电脑的函数。但我也想在关闭之前关闭所有打开的窗口。那么是否有任何 python 脚本可以做到这一点或任何 windows 快捷键?

【问题讨论】:

  • 尝试taskkill /im explorer.exe -f 然后explorer
  • 这意味着我必须在 cmd 中编写 {taskkill /im explorer.exe -f} 吗? @sa_n__u
  • 没关系。不,不是 CMD,请查看 subprocess 模块文档
  • 好的!谢谢你的建议@OneCricketeer

标签: python windows windows-10


【解决方案1】:

您可以使用子进程执行powershell 或DOS shutdown 脚本:

import subprocess

# forced shutdown closes windows without saving; you might need to add shell=True 

COMMAND = "Stop-Computer -Force"
subprocess.run(['powershell', '-command', COMMAND], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

我们也可以关闭窗口然后关机


# replace command above with below
COMMAND  = """(New-Object -comObject Shell.Application).Windows() | foreach-object {$_.quit()}; Get-Process | Where-Object {$_.MainWindowTitle -ne \"\"} | stop-process; Stop-Computer"""

操作系统

# from shutdown documentation 
# /s  Shuts down the computer
# /f   Forces running applications to close without warning users.
# /t <xxx> Sets the time-out period before shutdown to xxx seconds.

subprocess.run(['shutdown', '/s', '/t 0', '/f'], shell=False)

【讨论】:

  • 如果我只想关闭所有打开的窗口,我该怎么办? @Prayson W.丹尼尔
猜你喜欢
  • 2011-03-25
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
  • 2018-12-25
  • 2013-08-29
相关资源
最近更新 更多