The solution is:
import subprocess
# restart
subprocess.Popen(r"C:\Windows\System32\shutdown.exe /r /t 0", creationflags=subprocess.CREATE_NO_WINDOW)
# power off
subprocess.Popen(r"C:\Windows\System32\shutdown.exe /p", creationflags=subprocess.CREATE_NO_WINDOW)
Context (pasted from @Mofi's comments):
os.system
is declared as deprecated since more than 10 years and should not be used anymore at all. There is the subprocess
module which gives a Python script writer the full control on Windows how an executable is run by calling the Windows kernel library function CreateProcess
without or with a STARTUPINFO
structure.
os.system()
calls the system function which on Windows results in calling CreateProcess
with %ComSpec%
(defined with %SystemRoot%\System32\cmd.exe
expanding usually to C:\Windows\System32\cmd.exe
) with the option /c
(run command line and close) and the command line passed as argument to os.system
appended as additional arguments for cmd.exe
.
In this case cmd.exe
searches for a file with name shutdown
in the current directory and next in the directories as listed in local environment variable PATH
with no file extension at all or with a file extension as listed in local environment variable PATHEXT
. It hopefully finds in this case after several file system accesses %SystemRoot%\System32\shutdown.exe
and calls now CreateProcess
to run this batch file with using the standard streams of cmd.exe
and waiting for self-termination of shutdown.exe
after which cmd.exe
closes itself.
There can be used os.environ
to get the string value of the environment variable SystemRoot
. This directory path string can next be concatenated with the string "\\System32\\shutdown.exe"
to get the fully qualified file name of the executable to run. It is very unlikely that the environment variable SystemRoot
is not defined at all. That is possible only if a user explicitly deletes this environment variable in a command prompt window before starting in same command prompt window Python for interpreting a Python script.
There should be used the string "C:\\Windows"
in case of environ["SystemRoot"]
returns no string (or an empty string). However, it is advisable to check the existence of finally determined fully qualified file name of the Windows command SHUTDOWN and inform the user if the executable is not existing instead of a blind execution of this executable and hoping it really exists although this is most likely always the case (at least now but who knows the future). Then subprocess.Popen()
can be used to run shutdown.exe
with its full path.
subprocess.Popen()
offers subprocess.CREATE_NO_WINDOW
for calling CreateProcess
with the Process Creation Flag CREATE_NO_WINDOW
set in dwCreationFlags
for not opening a new console window for the Windows console application shutdown.exe
.