How to shutdown a computer using Python How to shutdown a computer using Python windows windows

How to shutdown a computer using Python


import osos.system('shutdown -s')

This will work for you.


For Linux:

import osos.system('sudo shutdown now')

or: if you want immediate shutdown without sudo prompt for password, use the following for Ubuntu and similar distro's:

os.system('systemctl poweroff') 


Using ctypes you could use the ExitWindowsEx function to shutdown the computer.

Description from MSDN:

Logs off the interactive user, shuts down the system, or shuts down and restarts the system.


First some code:

import ctypesuser32 = ctypes.WinDLL('user32')user32.ExitWindowsEx(0x00000008, 0x00000000)

Now the explanation line by line:

  • Get the ctypes library
  • The ExitWindowsEx is provided by the user32.dll and needs to be loaded via WinDLL()
  • Call the ExitWindowsEx() function and pass the necessary parameters.

Parameters:

All the arguments are hexadecimals.

The first argument I selected:

shuts down the system and turns off the power. The system must support the power-off feature.

There are many other possible functions see the documentation for a complete list.

The second argument:

The second argument must give a reason for the shutdown, which is logged by the system. In this case I set it for Other issue but there are many to choose from. See this for a complete list.

Making it cross platform:

This can be combined with other methods to make it cross platform. For example:

import sysif sys.platform == 'win32':    import ctypes    user32 = ctypes.WinDLL('user32')    user32.ExitWindowsEx(0x00000008, 0x00000000)else:    import os    os.system('sudo shutdown now')

This is a Windows dependant function (although Linux/Mac will have an equivalent), but is a better solution than calling os.system() since a batch script called shutdown.bat will not conflict with the command (and causing a security hazard in the meantime).

In addition it does not bother users with a message saying "You are about to be signed out in less than a minute" like shutdown -s does, but executes silently.

As a side note use subprocess over os.system() (see Difference between subprocess.Popen and os.system)


As a side note: I built WinUtils (Windows only) which simplifies this a bit, however it should be faster (and does not require Ctypes) since it is built in C.

Example:

import WinUtilsWinUtils.Shutdown(WinUtils.SHTDN_REASON_MINOR_OTHER)