In the process of daily use of the computer, many small partners have the need for automatic computer shutdown. In general, there are several options available to you.

If one day, your goddess asked you if there is a good way to turn off your cell phone regularly, what would you tell her?


The first article states Mr. Blog:
Use Python to shut down the computer automatically. – Mr. StateAnd wechat official account: Mr. Zhou (ID: Zmister2016)

If you are familiar with computer operation, you can use CMD command

Some small friends are more familiar with the various operations of the computer, is a full computer, “the computer is repaired well, XXX when old”, cough. This kind of friend basically has the need through the computer operating system itself can solve the function. For example, when it comes to shutting down the computer, the computer will shutdown automatically with the shutdown command at the command line.

Yes, use shutdown from the command line to automatically shutdown the computer. The shutdown command is used to process computers and applications. There are a number of usage parameters, such as logging out of a computer.

shutdown /lCopy the code

To shut down the computer, use the following command:

shutdown /sCopy the code

To restart the computer, run the following command:

shurdown /rCopy the code

The following figure shows all parameters of the shutdown command:


As you can see from the figure above, we continue to use the /t parameter to timeout the shutdown operation, which is a timed operation. For example, if we need to shut down the computer after a minute, we can use the following command:

shutdown /s /t 60Copy the code

It’s easy, it’s quick. However, it can be a bit tedious if you need to do it frequently, every time you need to:

  • Open command line;
  • Calculate the number of seconds needed to shut down;
  • Enter shutdown;

If your goddess asked you, you tell her that the first XXX key to open the command line terminal, and then calculate the conversion when the key is needed, and finally enter a string of ghost command…… Well, goodbye to you.

Two, not familiar with the computer operation, diagram to save trouble to use online software

If you don’t want to open the command line terminal every time, calculate the time, enter the command, then you can use some written and developed timing shutdown small software.

There are dozens of such software on the Internet, and there is a ranking of shutdown software on a software download website, as shown below:


This type of software is basically installation-free, downloadable and complex to use. However, these small software, either from unknown sources, or advertising all over the place, if recommended to goddess use, it is really not assured. In case pop up what “XX live”, “Lisboa casino” and so on advertising, or induced download installation of a certain family barrel, is really damage their image in the heart of the goddess.

3. For ease and security, we can write it ourselves in Python

Don’t want to goddess operation trouble, but also worried about the Internet download software unreliable, then their own masturbation out of it. Python is a great way to write this kind of gadget helper software. Below, we write a simple timer automatic shutdown through PyQt5 small assistant.

The core code

On many occasions, we have heard of the so-called 80-20 rule, where the 20 percent of the parts account for 80 percent of the action. In this periodic shutdown of the little assistant, may also exist in this law.

The core code for shutdown using Python is to use Python’s subprocess library to execute shutdown as follows:

subprocess.call("shutdown /p")Copy the code

Of course, there’s no way our timer shutdown assistant is just one line of code, so we might as well have the goddess use shutdown directly on the command line terminal.

In order to make this line of core code easy to use and simple packaging, we need to use PyQt5 this graphical interface framework to write a shell out, the timing shutdown code packaging.

The graphical interface

First, we create a basic graphical interface using QMainWindow:

# coding: UTF-8 from PyQt5 import QtWidgets,QtGui,QtCore import sys import datetime import subprocess "" class MainUi(QtWidgets.QMainWindow): def __init__(self,parent=None): super().__init__() self.init_ui() self.timer_status = False def init_ui(self): Self.setfixedsize (500, 350) # def main(): self.setFixedSize(500, 350) def main(): app = QtWidgets.QApplication(sys.argv) gui = MainUi() gui.show() sys.exit(app.exec_()) if __name__ == '__main__': main()Copy the code

The code should look like this:


Next, we set up ICONS for the interface and add two widgets using the grid QGridLayout(). In the upper grid, we add the current time via QLabel(), countdown time and a picture LOGO button via QPushbutton(). Use QTabWidget() to create TAB widgets in the grid below:

# set icon = qtgui.qicon () icon.addpixMap (qtgui.qpixmap ("gj.png"), qtgui.qicon.normal, Qtgui.qicon.off) self.setwindowIcon (icon) # Main widget self.main_widget = qtwidgets.qwidget () # instantiate a QWidget, SetObjectName ('main_widget') self.main_layout = qtwidgets.qgridLayout () # Create a grid layout Self.main_widget. setLayout(self.main_layout) # setStyleSheet(" "#datetime_label{font-size:20px; font-weight:700; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } #at_icon{ background-image: url(./alogo.png); width:175px; height:70px; } #start_timer,#start_time{ width:40px; height:40px; border:3px solid black; border-radius:10px } #timer_custom_input{ width:5px; } #timer_lable{ color:red; font-size:16px; font-weight:700; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } QTabBar::tab{ min-width:40ex; min-height:10ex; } "") # Two child widgets self.widget_top = qtwidgets.qwidget () # Top widget self.widget_top_layout = qtwidgets.qgridLayout () # create a grid layout Self.widget_top.setlayout (self.widget_top_layout) # Sets widget_top layout to grid layout self.datetime_label = qtwidgets.qlabel () # Create a date-time text self.datetime_label.setobJectName ('datetime_label') Self. Datetime_label. SetText (datetime. Datetime. Strftime (datetime) datetime) today (), "% % Y - m - H: % d % % m: % S")) # set the text content for the current time Self.timer_lable = qtwidgets.qlabel () # countdown text self.timer_lable. SetObjectName ('timer_lable') self.shutdown_lable = Self.attention_img = qtwidgets.qpushbutton () # Create a button Self.attention_img. setObjectName('at_icon') # add the widget to the top layout self.widget_top_layout.addwidget (self.datetime_label,0,0,1,3)  self.widget_top_layout.addWidget(self.timer_lable, 1, 0, 1, Self.widget_top_layout.addwidget (self.attention_img,0,4) self.widget_bottom = qtwidgets.qtabwidget () # Countdown auto Shutdown self.timer_Tab = qtwidgets.qtabWidget () # Create a TAB self.timer_tab_layout = qtwidgets.qGridLayout () # Create a grid layout Self.timer_tab.setlayout (self.timer_tab_layout) # Set TAB layout to grid self.timer_10 = qtwidgets.qradioButton ("10 minutes ") # create radio button Self.timer_10.setobjectname ('timer_button') self.timer_15 = qtwidgets.qradiobutton ("15分钟") Self.timer_10.setobjectname ('timer_button') self.timer_30 = qtwidgets. QRadioButton("30 minutes ") self.timer_60 = QRadioButton("60 minutes ") self.timer_60.setChecked(True) # set self.timer_90 = qtwidgets.qradiobutton ("90 minutes ") Self.timer_custom = qtwidgets.qtimeEdit () # Time select input box self.timer_Custom.setDisplayFormat ("HH:mm:ss") # set time select box format Self.timer_shutdown = qtwidgets.qpushButton ("start countdown ") self.timer_shutdown. SetObjectName ("start_timer") Self. Timer_tab_layout. AddWidget (self) timer_10, 0, 0) self. Timer_tab_layout. AddWidget (self timer_15, 0, 1) self.timer_tab_layout.addWidget(self.timer_30, 1, 0) self.timer_tab_layout.addWidget(self.timer_60, 1, 1) self.timer_tab_layout.addWidget(self.timer_90, 2, 0) self.timer_tab_layout.addWidget(self.timer_custom, 2, 1,1,1 self. Timer_tab_layout. AddWidget (self timer_shutdown, 0, Self.sletime_tab = qtwidgets.qtabWidget () self.sletime_tab_layout = qtwidgets.qgridLayout () self.sletime_tab_layout = qtwidgets.qgridLayout Self.sletime_tab.setlayout (self.sletime_tab_layout) self.time_custom = qtwidgets.qdatetimeEdit () # select time to shutdown self.time_custom.setDateTime(datetime.datetime.today()) self.time_custom.setDisplayFormat("yyyy-MM-dd HH:mm:ss") # Self.time_shutdown = qtwidgets. QPushButton(" shutdown at specified time ") self.time_shutdown.setobjectName ('start_time') Self. Sletime_tab_layout. AddWidget (self time_custom, 0, 2) Self.sletime_tab_layout.addwidget (self.time_shutdown,0,2,1,1) self.widget_bottom.addtab (self.timer_tab," countdown shutdown ") Self.main_layout. AddWidget (self.widget_top,0,0,1,1) self.widget_top (self.widget_top,0,0,1,1) self.main_layout.addWidget(self.widget_bottom, 1, 0, 2, 0) self.setCentralWidget(self.main_widget) # set the UI core widget to main_widgetCopy the code

So our graphical interface should look like the following:


However, the current time displayed on the interface is only the time when the program starts, and will not change in real time. Next, we will realize the real-time change of the current time on the interface.

In MainUi(), create a new method that sets the text of self.datetime_label:

Def show_datetime_slots(self): self.datetime_label.setText(datetime.datetime.strftime(datetime.datetime.today(),"%Y-%m-%d %H:%M:%S"))Copy the code

Then, create a timer in the init_ui() method, set the timer interval to 1 second, bind the timer to the show_datetime_slots() method, and start the timer:

# real time timer self. Datetime = QtCore. QTimer () # instantiate a timer self. The datetime. SetInterval (# 1000) set the timer interval of 1 second self. A datetime. # start () Start the timer self. Datetime. A timeout. Connect (self. Show_datetime_slots) # timer is connected to the slot time function to update the UI interfaceCopy the code

With these two steps completed, the time in our graphical interface can change in real time:

Next, handle the button operation, when we click the button, get the selected or set time value, disable all radio buttons and time selection boxes, and start the newly created timer self.timer_time for counting down, when the countdown is over, connect to the slot function:

Def show_timer_slots(self): try: if self.secound == 0: self.timer_time.stop() subprocess.call("shutdown /p") else: self.secound -= 1 m, s = divmod(self.secound, 60) h, m = divmod(m, 60) print("%02d:%02d:%02d" % (h, m, S)) self.timer_lable. SetText (" countdown :%02d:%02d :%02d "% (h, m, s)) except Exception as e: Def start_timer_shutdown(self): if self.timer_status is False: Self.timer_status = True self.timer_shutdown.settext (" Stop countdown ") self.timer_10.setenabled (False) self.timer_15.setEnabled(False) self.timer_30.setEnabled(False) self.timer_60.setEnabled(False) self.timer_90.setEnabled(False) self.timer_custom.setEnabled(False) self.time_custom.setEnabled(False) self.time_shutdown.setEnabled(False) if self.timer_custom.text() ! = '00:00:00' : Print (" use custom time ") h, m, s = self.timer_custom.text().strip().split(":") self.secound = int(h) * 3600 + int(m) * 60 + int(s) else: Print (" use default time ") if self.timer_10.ischecked () is True: self.secound = int(self.timer_10.text()[:2]) * 60 elif self.timer_15.isChecked() is True: self.secound = int(self.timer_15.text()[:2]) * 60 elif self.timer_30.isChecked() is True: self.secound = int(self.timer_30.text()[:2]) * 60 elif self.timer_60.isChecked() is True: self.secound = int(self.timer_60.text()[:2]) * 60 elif self.timer_90.isChecked() is True: self.secound = int(self.timer_90.text()[:2]) * 60 self.timer_time.start() Self.timer_time.timeout. connect(self.show_timer_slots) # timer connect to slot function update UI time else: Self.timer_status = False self.timer_shutdown.settext (" start countdown ") self.timer_time.stop() # stop countdown timer Self.timer_lable. SetText (" Countdown has stopped!" ) # re-enable self.timer_10.setenabled (True) self.timer_15.setenabled (True) self.timer_30.setenabled (True) self.timer_60.setEnabled(True) self.timer_90.setEnabled(True) self.timer_custom.setEnabled(True) SetEnabled (True) # def start_time_shutdown(self): self.time_custom.setenabled (True) # def start_time_shutdown(self): If self.timer_status is False: self.timer_status = True self.time_shutdown.settext (" Stop countdown!") ) self.timer_10.setEnabled(False) self.timer_15.setEnabled(False) self.timer_30.setEnabled(False) self.timer_60.setEnabled(False) self.timer_90.setEnabled(False) self.timer_custom.setEnabled(False) self.time_custom.setEnabled(False) self.timer_shutdown.setEnabled(False) set_time = Datetime. Datetime. Strptime (self) time_custom) text (), "% % Y - m - H: % d % % m: % S") # reduction set time time form print (self) time_custom) text ()) Time_delta = (set_time-datetime.datetime.today ()).total_seconds() print(time_delta) if int(time_delta) > Zero: Self.secound = time_delta self.timer_time.start() # Start timer self.timer_time.timeout.connect(self.show_timer_slots) # Timer connect to slot function update UI time else: Self.timer_status = False self.time_shutdown.settext (" shutdown at specified time ") self.timer_time.stop() # stop the countdown timer Self.timer_lable. SetText (" Countdown has stopped!" ) # re-enable self.timer_10.setenabled (True) self.timer_15.setenabled (True) self.timer_30.setenabled (True) self.timer_60.setEnabled(True) self.timer_90.setEnabled(True) self.timer_custom.setEnabled(True) self.time_custom.setEnabled(True) self.timer_shutdown.setEnabled(True)Copy the code

Thus, when we select a countdown and click the Start button, a reminder of the countdown appears in the graphical interface and all options are disabled, as shown in the following GIF:

Packaging EXE

Program prepared, the use of Pyinstaller and other tools to package it into an EXE file, you can no problem to goddess use. In this case, Kyoshi is using the Pyinstaller 3.4 development release.

Before packaging, we need to do some processing on the image file referenced in the code, so that the packaged program can not index the image. In this program, we use two images, one is a small icon of the GUI, and the other is a large LOGO in the upper right corner of the GUI. We create a QRC file named img. QRC for these two images, and the content is:

<RCC>
  <qresource prefix="/" >
    <file>gj.png</file>
    <file>alogo.png</file>
  </qresource>
</RCC>Copy the code

Then, in the same directory as the img. QRC file, open the command line and type:

pyrcc5 img.qrc -o imgs.pyCopy the code

Executing the command will generate a Python file named imgs.py in the current directory that contains the Base64 encoded content of the image we defined.

Then introduce this file into the program’s code:

import imgsCopy the code

At the same time, modify the way of using the picture by adding a colon: before the path of the picture, as shown below:

icon.addPixmap(QtGui.QPixmap(":gj.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)Copy the code

Big logo:

background-image: url(:alogo.png);Copy the code

Once this is done, you can package the program using the Pyinstaller. In the file directory, we open the command line terminal and enter the command:

pyinstaller -F -w --icon favicon.ico xxx.pyCopy the code

Among them:

  • -f: packages the program as an EXE file.
  • -w: indicates that the default console is not configured.
  • – ICO: specifies the icon of the generated EXE file.

In the dist folder, the EXE program is stored in the build and dist subfolders:




Open EXE file file, the program runs all normal:

So we’re done with the automatic shutdown helper we wrote in Python.

If you need source files and EXE files, you can pay attention to wechat public number: Mr. State, reply keyword “0012” to obtain. Welcome to comment!