Python turn off computer

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

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

Это делает своего рода выключение, но остается на включенной панели управления Windows (где пользователь может переключать пользователей компьютера). Есть ли способ полностью выключить компьютер? Я пробовал другие os.system(«shutdown ___») безуспешно. Есть ли другой метод, который может помочь?

На самом деле это не имеет ничего общего с Python, так как shutdown /p просто отправляется в систему как команда терминала. Пожалуйста, укажите версию вашей ОС, так как параметры могут отличаться.

Да, конечно. Но мой вопрос: есть ли способ использовать модули Python? или по-другому? И мне нужно запустить программу на нескольких компьютерах, поэтому версия ОС не совпадает. Спасибо

5 ответов

import os os.system('shutdown -s') 

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

Одна из проблем заключается в том, что он оставляет сообщение о том, что «You are about to be signed out in less than a minute» . Другая причина заключается в том, что если кто-то разместит пакетный сценарий с именем shutdown.bat вместе со сценарием, он не будет работать, это также является угрозой безопасности, поскольку этот файл будет выполнен. Подпроцесс теперь должен использоваться поверх os.system() .

import os os.system('sudo shutdown now') 

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

os.system('systemctl poweroff') 

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

import os os.system('shutdown /p /f') 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Это зависимая от 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.

import WinUtils WinUtils.Shutdown(WinUtils.SHTDN_REASON_MINOR_OTHER) 

Источник

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:

import os os.system("shutdown /s")

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:

import os os.system("shutdown /s /t 0")

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:

import os print("Enter Number of Seconds to Shutdown System: ") sec = int(input()) strOne = "shutdown /s /t " strTwo = str(sec) str = strOne+strTwo os.system(str)

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:

import os; os.system("shutdown /r")

Restart Computer Immediately

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

import os os.system("shutdown /r /t 0")

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:

import os print("1. Shutdown Computer Immediately") print("2. Shutdown Computer after Given Time") print("3. Restart Computer Immediately") print("4. Restart Computer after Given Time") print("5. Exit") print(end="Enter Your Choice: ") choice = int(input()) if choice==1: os.system("shutdown /s /t 0") elif choice==2: print(end="Enter Number of Seconds: ") sec = int(input()) strOne = "shutdown /s /t " strTwo = str(sec) str = strOne+strTwo os.system(str) elif choice==3: os.system("shutdown /r /t 0") elif choice==4: print(end="Enter Number of Seconds: ") sec = int(input()) strOne = "shutdown /r /t " strTwo = str(sec) str = strOne+strTwo os.system(str) elif choice==5: exit() else: print("Wrong Choice!")

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.

Shutdown Linux Based System

To shutdown linux based system using a Python program, here is the code:

import os os.system("sudo shutdown now")

This program shutdown the linux based system immediately.

Same Program in Other Languages

Liked this article? Share it!

Источник

How To Shutdown Restart or Logoff your Windows Computer using Python Program

You can Shutdown or restart or logoff your windows computer from a python program by using shutdown program present in system32 folder.

we are using the system function available in the os library.

Example Python Program to Shutdown your Computer

 1 import os 2 3 choice = input("Shut Down your Computer ? ( y or n ) ") 4 5 if choice == 'y' or choice == 'Y': 6 os.system("shutdown /s") 7 else: 8 print("Exiting the program doing nothing")

Example Python Program to Restart your Computer

 1 import os 2 3 choice = input("Restart your Computer ? ( y or n ) ") 4 5 if choice == 'y' or choice == 'Y': 6 os.system("shutdown /r") 7 else: 8 print("Exiting the program doing nothing")

Example Python Program to Logoff your Computer

 1 import os 2 3 choice = input("Logoff your Computer ? ( y or n ) ") 4 5 if choice == 'y' or choice == 'Y': 6 os.system("shutdown /l") 7 else: 8 print("Exiting the program doing nothing")

Watch this video to learn how this works

Источник

Читайте также:  Дата на английском php
Оцените статью