Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

How to close all opened windows from python?

I am making a personal voice assistant in python. And in my program I wrote a function which can shutdown my pc. But I also want to close all opened window before shutting down. So is there any python script to do that or any windows shortcut key?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can execute powershell or DOS shutdown script using subprocess:

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)

We can also close windows and then shutdown


# 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"""

DOS

# 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...