Как выключить компьютер через python
Перейти к содержимому

Как выключить компьютер через python

  • автор:

Как выключить компьютер с помощью Python

Я написал сценарий Python, который должен в конечном итоге выключить компьютер.

Эта строка является ее частью:

Это делает своего рода выключение, но остается на включенной панели управления Windows (где пользователь может переключать пользователей компьютера).

Есть ли способ полностью выключить компьютер?

Я пробовал другие os.system(«shutdown ___») безуспешно.

Есть ли другой метод, который может помочь?

5 ответов

Это будет работать для вас.

или: если вы хотите немедленное отключение без запроса sudo для sudo пароля, используйте следующее для Ubuntu и подобных дистрибутивов:

Единственный вариант, который действительно работает для меня без каких-либо проблем:

Используя ctypes, вы можете использовать функцию ExitWindowsEx для выключения компьютера.

Описание из MSDN:

Выход из системы интерактивного пользователя, выключение системы или выключение и перезагрузка системы.

Сначала немного кода:

Теперь объяснение построчно:

  • Получить библиотеку ctypes
  • ExitWindowsEx предоставляется user32.dll и должен быть загружен через WinDLL()
  • Вызовите ExitWindowsEx() и передайте необходимые параметры.

Параметры:

Все аргументы шестнадцатеричные.

Первый аргумент, который я выбрал:

выключает систему и выключает питание. Система должна поддерживать функцию отключения питания.

Есть много других возможных функций, см. Документацию для полного списка.

Второй аргумент должен дать причину отключения, которое регистрируется системой. В этом случае я выбрал Other issue вариант, но есть из чего выбирать. Смотрите это для полного списка.

Делаем это кроссплатформенным:

Это может быть объединено с другими методами, чтобы сделать его кроссплатформенным. Например:

Это зависимая от Windows функция (хотя Linux/Mac будет иметь аналог), но это лучшее решение, чем вызов os.system() поскольку пакетный скрипт с именем shutdown.bat не будет конфликтовать с командой (и вызывать угрозу безопасности в тем временем).

Кроме того, он не беспокоит пользователей сообщением «You are about to be signed out in less than a minute» как shutdown -s делает shutdown -s , но выполняется без вывода сообщений.

В качестве дополнительного примечания используйте подпроцесс над os.system() (см. Различие между subprocess.Popen и os.system)

В качестве примечания: я создал WinUtils (только для Windows), который немного упрощает это, однако он должен быть быстрее (и не требует Ctypes), поскольку он встроен в C.

Shutdown and Restart PC using Python

In this tutorial, we are going to learn how to Shutdown and restart the PC using Python. For this firstly, we need to import the OS module in our code. OS is an inbuilt module present in Python. Let’s know something about the OS module.

Shutdown and restart PC using OS Module in Python

The OS module in Python consists of functions that work on Operating Systems like Windows , Mac or Linux . Let us see the program.

In the above program, we have imported the os module and we are entering a value for the ‘a’ variable. If we enter 1 the PC will shut down and if we enter 2 the PC will restart. We are giving a command in the system function present in the OS module.

The system will shut down/restart immediately after you enter the input. So ensure that all other applications are closed and any unsaved work is saved.

How to shutdown a computer using Python

I’ve written a Python script which should eventually shutdown the computer.

This line is a part of it :

It makes some sort of a shutdown but remains on the turn-on Windows control pannel (where the user can switch the computer users).

Is there a way to fully shutdown the computer?

I’ve tried other os.system(«shutdown ___») methods with no success.

Is there another method which might help?

10 Answers 10

This will work for you.

shiva1791's user avatar

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

Xantium's user avatar

Mtl Dev's user avatar

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:

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:

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: 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.

Python Program to Shutdown and Restart Computer

In this article, you will learn and get code in Python, to shutdown or restart the computer system. Here are the list program programs available over here:

  • Shutdown Computer
  • Shutdown Computer Immediately
  • Shutdown Computer in Given Time by User
  • Restart Computer
  • Restart Computer Immediately
  • Restart Computer in Given Time by User
  • Shutdown/Restart Computer based on User’s Choice
  • Shutdown Linux Based System

Note — All python programs (on Shutdown/Restart) given in this article, are well-tested and executed. Therefore be sure to save all documents before executing any program given here.

Caution — Make sure to save and close all documents before executing any program given below. Because after executing these codes (programs), your system gets shutdown/restart and you can lost your unsaved documents.

To shutdown or restart your computer system (PC or laptop) using a python code, you have to first import the os library and then use os.system() in this way:

to shutdown the system. Replace /s with /r to restart the system. Now let’s create the program in Python to do the task.

Shutdown Computer using Python

This python program shutdown your computer system after default time, that is 30 seconds. As soon as you run the program given below, your computer gets shutdown after 30 seconds:

Note — Close all documents before executing this program.

Note — The os module provides functions to interact with Operating System.

Note — The os.system() method is used to execute a command in a subshell. Here, the command is of string type.

Shutdown Computer Immediately

To shutdown the system immediately, provide the timer as 0 second. So that the system gets shutdown within 0 second or immediately as shown in this program:

Note — The /t 0 is extra code added in this program (than previous one). Here /t stands for timer and 0 indicates 0 second. Therefore after executing this program, system gets shutdown within 0 second.

Shutdown Computer in Given Time

This program asks from user to enter the number of seconds to set the timer to shutdown the system:

Here is the initial output produced by this python program:

python shutdown computer

Now enter the number of seconds say 10 to shutdown the system in 10 seconds.

Note — The str(sec) is used to convert sec (an integer type value) to string. Because to use + operator to concatenate two string values. That is, strOne and strTwo. The second string is the timer value entered by user.

Restart Computer using Python

To restart your computer system using a python program, just replace the /s with /r from the program given to shutdown the system. Rest of the things will be same as shown in the program given below:

Restart Computer Immediately

This python program restarts your computer in 0 second or immediately:

Restart Computer in Given Time

This program is same as the program given in shutdown computer in given time section. The only thing to do is, replace the following statement:

with the statement given below:

Note — Just a matter of s and r, the whole program gets changed.

Note — Also replace the Shutdown word to Restart, from print message.

Shutdown & Restart based on User’s Choice

Here is the combined version of both programs, that is shutdown and restart program in python.

This python program asks from user to enter the choice to perform the desired action. That is, choices are given to perform the things such as shutdown immediately, shutdown in given time, and so on as shown in the program given below:

Here is the snapshot of the above python program, giving user, five options to proceed, what he/she wants to do. That is, either shutdown, restart or exit from the program:

python restart computer

If user enters 1 or 3 as choice, then the computer gets shutdown/restart just after pressing the ENTER key. And when user enters 2 as choice, then the program further asks to enter the number of seconds to shutdown the system:

python shutdown and restart computer

Now enter the input say 180 to shutdown the system after 180 seconds or 3 minutes.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *