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

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

Как сделать скрипт Python, который может выйти из системы, выключить и перезагрузить компьютер?

В настоящее время я нахожусь в процессе обучения самому Python, и я подумал, что было бы очень круто иметь своего рода «центр управления», в котором я мог бы выключать, перезагружать и выходить из своего компьютера. Я также хочу использовать модуль подпроцесса, поскольку я слышал, что модуль импорта ОС устарел.

Текущий код

Вопрос

На самом деле я спрашиваю: есть ли способ (с помощью модуля подпроцесса) выйти из системы и перезагрузить компьютер?

Технические характеристики

Windows 7, 32 бит

3 ответа

Окончательный кодовый блок (по запросу):

Если вы не можете заставить shutdown работать как-то, вы всегда можете просто вызвать функцию, которую она вызывает, из библиотеки USER. Вы могли бы сделать это через ctypes или win32api , но вы также можете просто сделать это:

Или вы можете вызвать функцию оболочки более высокого уровня, которую использует меню «Пуск»:

(См. Документацию MSDN по этим функциям.)

Я думаю, что это, вероятно, худший способ сделать это. Если вы хотите выполнить команду, запустите shutdown ; если вы хотите использовать API, используйте win32api . Но если у вас есть странно испорченная система, где shutdown /r просто не работает, это вариант.

Для начала вам необходимо:

Чтобы выключить компьютер с Windows:

Чтобы перезагрузить компьютер с Windows

Чтобы выйти из ПК с Windows:

Чтобы выключить компьютер с Windows через 900 секунд:

Чтобы прервать выключение, потому что нет веской причины выключать ваш компьютер с помощью скрипта Python, вы просто скопировали код из stackoverflow:

Я только пробовал эти вызовы функций в Python 3.5. Во-первых, я не думаю, что это изменилось со времен Python 2.7, а во-вторых: это 2016, так что я думаю, что вы сделали переход уже после того, как задали этот вопрос.

AlexanderNest/Computer-control

Утилита для управления компьютером. Выключение (по таймеру), перезагрузка, спящий режим. Python 3 Разработана для управления ПК под ОС Linux Разработан графический интерфейс. Функции:

  • Выключение компьютера
  • Выключение компьютера по таймеру
  • Перезагрузка компьютера
  • Переход в спящий режим
  • Отмена заданного таймера

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

About

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

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 не будет опубликован. Обязательные поля помечены *