python做了个自动关机工具,再也不会耽误我下班啦
上班族经常会遇到这样情况,着急下班结果将关机误点成重启,或者临近下班又通知开会,开完会已经迟了还要去给电脑关机。
今天使用PyQt5做了个自动关机的小工具,设置好关机时间然后直接提交即可,下班就可以直接走人了。
有直接需要.exe可执行应用的话,直接到文末处获取下载链接!
自动关机小工具也支持了清除已经设置好的关机时间,防止已经设置好了关机时间重新调整时不知道怎么调整。
本应用除了使用os的python标准库来设置关机,还引入了PyQt5的桌面应用框架,通过实现自动设置关机命令以及清除操作来完成。
# Importing the QThread, QDateTime, and pyqtSignal classes from the PyQt5.QtCore module. from PyQt5.QtCore import QThread, QDateTime, pyqtSignal # Importing the QIcon and QFont classes from the PyQt5.QtGui module. from PyQt5.QtGui import QIcon, QFont # Importing the QWidget, QLabel, QDateTimeEdit, QPushButton, QFormLayout, and QApplication classes from the # PyQt5.QtWidgets module. from PyQt5.QtWidgets import QWidget, QLabel, QDateTimeEdit, QPushButton, QFormLayout, QApplication # Importing the os, sys, and time modules. import os, sys, time # Importing the images.py file. import images
创建CloseCompUI的class类,用来实现自动关机应用的页面布局,将UI相关以及对应的槽函数写到这个类中。
上面的就是已经设置好的界面布局及需要的组件信息,然后将组件信息以及信号量关联到槽函数上实现相应的动态操作。
下面是所有相关的槽函数,同样这些槽函数是放在CloseCompUI的class中的。
创建CloseCompThread的class类,作为单独的子线程独立运行不影响主线程的执行,将所有的业务模块(具体的关机实现)写到该线程中。
# This class is a QThread that runs a function that takes a list of strings and returns a list of strings
class CloseCompThread(QThread):
message = pyqtSignal(str)
def __init__(self, parent=None):
"""
A constructor that initializes the class.
:param parent: The parent widget
"""
super(CloseCompThread, self).__init__(parent)
self.parent = parent
self.working = True
def __del__(self):
"""
If the shutdown time is set, the shutdown thread is started, otherwise the message is displayed
"""
self.working = False
self.wait()
def run(self):
"""
*|CURSOR_MARCADOR|*
"""
try:
is_close = self.parent.is_close
print(is_close)
if is_close is True:
shutdown_time_in = self.parent.shutdown_time_in.text()
t = time.strptime(shutdown_time_in, "%Y-%m-%d %H:%M:%S")
t1 = int(time.mktime(t))
t0 = int(time.time())
num = t1 - t0
if num > 0:
os.system(shutdown -s -t %d % num)
self.message.emit("此电脑将在%s关机" % shutdown_time_in)
else:
self.message.emit("关机时间不能小于当前操作系统时间")
else:
os.system(shutdown -a)
self.message.emit("已经清除自动关机设置")
except:
self.message.emit("提交/清除自动关机出现错误")
开发子线程CloseCompThread的业务实现后基本上已经大功告成了,接下来使用main函数直接整个桌面启动就OK了。
# A common idiom in Python to use this to guard the main body of your code.
if __name__ == __main__:
app = QApplication(sys.argv)
main = CloseCompUI()
main.show()
sys.exit(app.exec_())
上述自动关机小工具应用中所有的代码块已经过测试,可以直接启动使用。应用中只使用了一个PyQt5的python非标准库需要安装,其他的不需要安装。
【往期精彩】
