在Python中实现自动关机可以通过多种方式,以下是几种常见的方法:
方法一:使用`os.system`执行`shutdown`命令
import osfrom datetime import datetime, timedef shutdown_pc(minutes_from_now):shutdown_time = datetime.now() + datetime.timedelta(minutes=minutes_from_now)time_to_shutdown = shutdown_time.strftime("%H:%M")os.system(f'shutdown -s -t {int((shutdown_time - datetime.now()).total_seconds())} -c "Scheduled shutdown at {time_to_shutdown}"')用户输入关机时间(分钟)minutes = int(input("请输入关机时间(分钟):"))shutdown_pc(minutes)
import tkinter as tkfrom tkinter import messageboximport osfrom datetime import datetime, timedeltadef shutdown_pc(minutes_from_now):shutdown_time = datetime.now() + timedelta(minutes=minutes_from_now)time_to_shutdown = shutdown_time.strftime("%H:%M")messagebox.showinfo("关机提示", f"将在 {time_to_shutdown} 关机。请保存工作并退出。")os.system(f'shutdown -s -t {int((shutdown_time - datetime.now()).total_seconds())} -c "Scheduled shutdown at {time_to_shutdown}"')创建主窗口root = tk.Tk()root.title("自动关机程序")获取关机时间输入shutdown_time_entry = tk.Entry(root)shutdown_time_entry.pack()获取关机按钮shutdown_button = tk.Button(root, text="选择并关机", command=lambda: shutdown_pc(int(shutdown_time_entry.get())))shutdown_button.pack()运行主循环root.mainloop()

方法三:使用`PyQt5`创建桌面应用
import sysfrom PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QDateTimeEdit, QPushButtonfrom PyQt5.QtCore import QTimerclass ShutdownApp(QWidget):def __init__(self):super().__init__()self.initUI()def initUI(self):self.setWindowTitle('自动关机程序')self.setGeometry(300, 300, 200, 150)layout = QVBoxLayout()self.label = QLabel('请设置关机时间(HH:MM):', self)layout.addWidget(self.label)self.time_edit = QDateTimeEdit(self)self.time_edit.setCalendarPopup(True)layout.addWidget(self.time_edit)self.button = QPushButton('选择并关机', self)self.button.clicked.connect(self.shutdown_pc)layout.addWidget(self.button)self.setLayout(layout)def shutdown_pc(self):shutdown_time = self.time_edit.dateTime().time()shutdown_time_str = shutdown_time.toString('HH:mm')messagebox.showinfo("关机提示", f"将在 {shutdown_time_str} 关机。请保存工作并退出。")os.system(f'shutdown -s -t {int((datetime.now() - datetime.now().time() + timedelta(hours=shutdown_time.hour, minutes=shutdown_time.minute)).total_seconds())} -c "Scheduled shutdown at {shutdown_time_str}"')if __name__ == '__main__':app = QApplication(sys.argv)ex = ShutdownApp()ex.show()sys.exit(app.exec_())
以上代码展示了如何使用Python实现自动关机功能,包括命令行界面和图形用户界面两种方式。您可以根据需要选择合适的方法进行实现。
