Python 设置电脑定时关机的方法详解
本文将介绍几种使用 Python 设置电脑定时关机的方法,并提供完整的代码示例。
方法一:使用 os.system 或 subprocess 调用系统命令
1.1 Windows 系统
import os
import time
def shutdown_windows(seconds=60):
"""
在 Windows 系统中定时关机
:param seconds: 延迟时间(秒)
"""
try:
# 计算关机时间
shutdown_time = seconds
os.system(f"shutdown /s /t {shutdown_time}")
print(f"系统将在 {shutdown_time} 秒后关机")
print("如果要取消关机,请运行: shutdown /a")
except Exception as e:
print(f"设置关机失败: {e}")
def cancel_shutdown_windows():
"""取消 Windows 系统的关机计划"""
try:
os.system("shutdown /a")
print("关机计划已取消")
except Exception as e:
print(f"取消关机失败: {e}")
# 使用示例
if __name__ == "__main__":
# 设置 1 小时后关机(3600 秒)
shutdown_windows(3600)
# 取消关机(取消上面的注释来测试)
# cancel_shutdown_windows()
1.2 Linux/Mac 系统
import os
import sys
def shutdown_linux(seconds=60):
"""
在 Linux/Mac 系统中定时关机
:param seconds: 延迟时间(秒)
"""
try:
# 检查是否有管理员权限
if os.geteuid() != 0:
print("注意:需要管理员权限才能执行关机操作")
print("请使用 sudo 运行此脚本")
return
# 使用 shutdown 命令
minutes = max(1, seconds // 60) # 至少1分钟
os.system(f"shutdown -h +{minutes}")
print(f"系统将在 {minutes} 分钟后关机")
print("如果要取消关机,请运行: shutdown -c")
except Exception as e:
print(f"设置关机失败: {e}")
def cancel_shutdown_linux():
"""取消 Linux/Mac 系统的关机计划"""
try:
os.system("shutdown -c")
print("关机计划已取消")
except Exception as e:
print(f"取消关机失败: {e}")
# 使用示例
if __name__ == "__main__":
# 设置 30 分钟后关机
shutdown_linux(1800)
# 取消关机(取消上面的注释来测试)
# cancel_shutdown_linux()
方法二:使用 schedule 库实现定时任务
import os
import platform
import schedule
import time
from datetime import datetime, timedelta
class AutoShutdown:
"""自动关机类"""
def __init__(self):
self.system = platform.system()
print(f"检测到系统: {self.system}")
def shutdown(self):
"""执行关机命令"""
try:
if self.system == "Windows":
os.system("shutdown /s /t 0")
elif self.system in ["Linux", "Darwin"]: # Darwin 是 Mac OS
if os.geteuid() != 0:
print("需要管理员权限,关机操作被跳过")
return
os.system("shutdown -h now")
else:
print(f"不支持的系统: {self.system}")
except Exception as e:
print(f"关机失败: {e}")
def schedule_shutdown_at(self, hour, minute):
"""
在指定时间关机
:param hour: 小时 (0-23)
:param minute: 分钟 (0-59)
"""
print(f"已设置每日 {hour:02d}:{minute:02d} 自动关机")
# 设置定时任务
schedule.every().day.at(f"{hour:02d}:{minute:02d}").do(self.shutdown)
# 保持脚本运行
try:
while True:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
print("\n定时关机任务已取消")
def schedule_shutdown_after(self, hours=0, minutes=0, seconds=0):
"""
在指定时间后关机
:param hours: 小时
:param minutes: 分钟
:param seconds: 秒
"""
total_seconds = hours * 3600 + minutes * 60 + seconds
if total_seconds <= 0:
print("时间必须大于0")
return
shutdown_time = datetime.now() + timedelta(seconds=total_seconds)
print(f"系统将在 {shutdown_time.strftime('%Y-%m-%d %H:%M:%S')} 关机")
# 计算延迟并执行关机
time.sleep(total_seconds)
self.shutdown()
# 使用示例
if __name__ == "__main__":
shutdown_manager = AutoShutdown()
# 方法1:在指定时间关机(例如:每天22:30关机)
# shutdown_manager.schedule_shutdown_at(22, 30)
# 方法2:在指定时间后关机(例如:2小时后关机)
shutdown_manager.schedule_shutdown_after(hours=2)
方法三:创建 GUI 界面的定时关机工具
import tkinter as tk
from tkinter import ttk, messagebox
import os
import platform
import threading
import time
class ShutdownGUI:
"""定时关机GUI应用程序"""
def __init__(self, root):
self.root = root
self.root.title("定时关机工具")
self.root.geometry("400x300")
self.system = platform.system()
self.create_widgets()
def create_widgets(self):
"""创建GUI组件"""
# 标题
title_label = tk.Label(self.root, text="定时关机工具",
font=("Arial", 16, "bold"))
title_label.pack(pady=10)
# 系统信息
sys_label = tk.Label(self.root, text=f"当前系统: {self.system}",
font=("Arial", 10))
sys_label.pack(pady=5)
# 时间设置框架
time_frame = tk.LabelFrame(self.root, text="关机时间设置", padx=10, pady=10)
time_frame.pack(pady=10, padx=20, fill="both")
# 小时设置
tk.Label(time_frame, text="小时:").grid(row=0, column=0, padx=5, pady=5)
self.hour_var = tk.IntVar(value=1)
hour_spin = tk.Spinbox(time_frame, from_=0, to=23,
textvariable=self.hour_var, width=5)
hour_spin.grid(row=0, column=1, padx=5, pady=5)
# 分钟设置
tk.Label(time_frame, text="分钟:").grid(row=0, column=2, padx=5, pady=5)
self.minute_var = tk.IntVar(value=0)
minute_spin = tk.Spinbox(time_frame, from_=0, to=59,
textvariable=self.minute_var, width=5)
minute_spin.grid(row=0, column=3, padx=5, pady=5)
# 秒设置
tk.Label(time_frame, text="秒:").grid(row=0, column=4, padx=5, pady=5)
self.second_var = tk.IntVar(value=0)
second_spin = tk.Spinbox(time_frame, from_=0, to=59,
textvariable=self.second_var, width=5)
second_spin.grid(row=0, column=5, padx=5, pady=5)
# 按钮框架
button_frame = tk.Frame(self.root)
button_frame.pack(pady=20)
# 设置关机按钮
set_btn = tk.Button(button_frame, text="设置定时关机",
command=self.set_shutdown, bg="green", fg="white",
width=15, height=2)
set_btn.grid(row=0, column=0, padx=10)
# 取消关机按钮
cancel_btn = tk.Button(button_frame, text="取消关机",
command=self.cancel_shutdown, bg="red", fg="white",
width=15, height=2)
cancel_btn.grid(row=0, column=1, padx=10)
# 状态标签
self.status_label = tk.Label(self.root, text="",
font=("Arial", 10), fg="blue")
self.status_label.pack(pady=10)
# 倒计时标签
self.countdown_label = tk.Label(self.root, text="",
font=("Arial", 12, "bold"), fg="red")
self.countdown_label.pack(pady=5)
def set_shutdown(self):
"""设置定时关机"""
hours = self.hour_var.get()
minutes = self.minute_var.get()
seconds = self.second_var.get()
total_seconds = hours * 3600 + minutes * 60 + seconds
if total_seconds <= 0:
messagebox.showwarning("警告", "请设置大于0的时间!")
return
# 在新线程中执行关机倒计时
thread = threading.Thread(target=self.countdown_and_shutdown,
args=(total_seconds,))
thread.daemon = True
thread.start()
self.status_label.config(text=f"已设置 {hours}小时{minutes}分钟{seconds}秒后关机")
def countdown_and_shutdown(self, total_seconds):
"""倒计时并关机"""
for i in range(total_seconds, 0, -1):
hours_left = i // 3600
minutes_left = (i % 3600) // 60
seconds_left = i % 60
countdown_text = f"剩余时间: {hours_left:02d}:{minutes_left:02d}:{seconds_left:02d}"
self.countdown_label.config(text=countdown_text)
time.sleep(1)
# 执行关机
self.execute_shutdown()
def execute_shutdown(self):
"""执行关机命令"""
try:
if self.system == "Windows":
os.system("shutdown /s /t 0")
elif self.system in ["Linux", "Darwin"]:
# 注意:在Linux/Mac上可能需要sudo权限
os.system("shutdown -h now")
else:
messagebox.showerror("错误", f"不支持的系统: {self.system}")
except Exception as e:
messagebox.showerror("错误", f"关机失败: {e}")
def cancel_shutdown(self):
"""取消关机计划"""
try:
if self.system == "Windows":
os.system("shutdown /a")
elif self.system in ["Linux", "Darwin"]:
os.system("shutdown -c")
self.status_label.config(text="关机计划已取消")
self.countdown_label.config(text="")
messagebox.showinfo("成功", "关机计划已取消")
except Exception as e:
messagebox.showerror("错误", f"取消关机失败: {e}")
# 主程序
if __name__ == "__main__":
root = tk.Tk()
app = ShutdownGUI(root)
root.mainloop()
方法四:使用系统任务计划(高级方法)
import os
import platform
import datetime
def schedule_shutdown_advanced(mode='daily', hour=22, minute=0):
"""
高级定时关机:使用系统任务计划
:param mode: 模式 'daily'每日, 'weekly'每周, 'once'一次
:param hour: 小时
:param minute: 分钟
"""
system = platform.system()
if system == "Windows":
# Windows 使用任务计划程序
task_name = "PythonAutoShutdown"
time_str = f"{hour:02d}:{minute:02d}"
if mode == 'daily':
# 创建每日任务
command = f'schtasks /create /tn "{task_name}" /tr "shutdown /s /f" /sc daily /st {time_str} /f'
elif mode == 'weekly':
# 创建每周任务(每周日)
command = f'schtasks /create /tn "{task_name}" /tr "shutdown /s /f" /sc weekly /d SUN /st {time_str} /f'
else:
# 一次性的任务
now = datetime.datetime.now()
target = now.replace(hour=hour, minute=minute)
if target <= now:
target += datetime.timedelta(days=1)
date_str = target.strftime("%Y-%m-%d")
command = f'schtasks /create /tn "{task_name}" /tr "shutdown /s /f" /sc once /st {time_str} /sd {date_str} /f'
os.system(command)
print(f"已创建系统任务,将在每天 {time_str} 自动关机")
# 显示任务
os.system(f'schtasks /query /tn "{task_name}"')
elif system in ["Linux", "Darwin"]:
# Linux/Mac 使用 crontab
cron_command = f"{minute} {hour} * * * shutdown -h now"
if mode == 'weekly':
# 每周日执行
cron_command = f"{minute} {hour} * * 0 shutdown -h now"
elif mode == 'once':
print("Linux一次性任务需要更复杂的实现,建议使用方法一或方法二")
return
# 添加到 crontab(注意:需要用户确认)
print(f"请将以下命令添加到 crontab:")
print(f" {cron_command}")
print("\n使用以下命令编辑 crontab:")
print(" crontab -e")
else:
print(f"不支持的系统: {system}")
def remove_scheduled_shutdown():
"""移除定时关机任务"""
system = platform.system()
task_name = "PythonAutoShutdown"
if system == "Windows":
os.system(f'schtasks /delete /tn "{task_name}" /f')
print("已删除定时关机任务")
elif system in ["Linux", "Darwin"]:
print("请手动编辑 crontab 移除相关行:")
print(" crontab -e")
else:
print(f"不支持的系统: {system}")
# 使用示例
if __name__ == "__main__":
# 创建每日22:00的定时关机任务
schedule_shutdown_advanced(mode='daily', hour=22, minute=0)
# 删除任务(取消注释来测试)
# remove_scheduled_shutdown()
完整示例:跨平台的命令行定时关机工具
#!/usr/bin/env python3
"""
定时关机工具 - 跨平台版本
用法: python shutdown_tool.py [选项]
"""
import argparse
import os
import platform
import time
import sys
class CrossPlatformShutdown:
"""跨平台定时关机类"""
def __init__(self):
self.system = platform.system()
self.is_admin = self.check_admin()
def check_admin(self):
"""检查管理员权限"""
try:
if self.system == "Windows":
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin() != 0
else:
return os.geteuid() == 0
except:
return False
def shutdown_now(self):
"""立即关机"""
if self.system == "Windows":
os.system("shutdown /s /f /t 0")
elif self.system in ["Linux", "Darwin"]:
if not self.is_admin:
print("需要管理员权限!请使用sudo运行。")
return
os.system("shutdown -h now")
else:
print(f"不支持的系统: {self.system}")
def shutdown_timed(self, seconds):
"""定时关机"""
if self.system == "Windows":
os.system(f"shutdown /s /t {seconds}")
print(f"Windows将在 {seconds} 秒后关机")
print("取消命令: shutdown /a")
elif self.system in ["Linux", "Darwin"]:
if not self.is_admin:
print("需要管理员权限!请使用sudo运行。")
return
minutes = max(1, seconds // 60)
os.system(f"shutdown -h +{minutes}")
print(f"系统将在 {minutes} 分钟后关机")
print("取消命令: shutdown -c")
else:
print(f"不支持的系统: {self.system}")
def shutdown_at(self, hour, minute):
"""在指定时间关机"""
now = time.localtime()
current_sec = now.tm_hour * 3600 + now.tm_min * 60 + now.tm_sec
target_sec = hour * 3600 + minute * 60
if target_sec <= current_sec:
target_sec += 24 * 3600 # 如果是今天已经过去的时间,则设置为明天
delay_seconds = target_sec - current_sec
print(f"将在 {hour:02d}:{minute:02d} 关机({delay_seconds} 秒后)")
self.shutdown_timed(delay_seconds)
def cancel_shutdown(self):
"""取消关机"""
if self.system == "Windows":
os.system("shutdown /a")
print("已取消关机计划")
elif self.system in ["Linux", "Darwin"]:
if not self.is_admin:
print("需要管理员权限!请使用sudo运行。")
return
os.system("shutdown -c")
print("已取消关机计划")
else:
print(f"不支持的系统: {self.system}")
def main():
parser = argparse.ArgumentParser(description="跨平台定时关机工具")
parser.add_argument("-t", "--time", type=int,
help="在指定秒数后关机")
parser.add_argument("-a", "--at",
help="在指定时间关机 (格式: HH:MM)")
parser.add_argument("-c", "--cancel", action="store_true",
help="取消关机计划")
parser.add_argument("-n", "--now", action="store_true",
help="立即关机")
args = parser.parse_args()
tool = CrossPlatformShutdown()
if args.now:
confirm = input("确定要立即关机吗?(y/N): ")
if confirm.lower() == 'y':
tool.shutdown_now()
else:
print("操作取消")
elif args.time:
tool.shutdown_timed(args.time)
elif args.at:
try:
hour, minute = map(int, args.at.split(':'))
if 0 <= hour <= 23 and 0 <= minute <= 59:
tool.shutdown_at(hour, minute)
else:
print("时间格式错误!")
except:
print("时间格式错误!请使用 HH:MM 格式")
elif args.cancel:
tool.cancel_shutdown()
else:
# 交互模式
print("=== 定时关机工具 ===")
print(f"系统: {tool.system}")
print(f"管理员权限: {'是' if tool.is_admin else '否'}")
print()
print("1. 立即关机")
print("2. 定时关机")
print("3. 指定时间关机")
print("4. 取消关机计划")
print("5. 退出")
choice = input("请选择操作 (1-5): ")
if choice == '1':
confirm = input("确定要立即关机吗?(y/N): ")
if confirm.lower() == 'y':
tool.shutdown_now()
elif choice == '2':
try:
seconds = int(input("请输入关机延迟时间(秒): "))
if seconds > 0:
tool.shutdown_timed(seconds)
else:
print("时间必须大于0!")
except:
print("无效的输入!")
elif choice == '3':
try:
time_str = input("请输入关机时间 (HH:MM): ")
hour, minute = map(int, time_str.split(':'))
if 0 <= hour <= 23 and 0 <= minute <= 59:
tool.shutdown_at(hour, minute)
else:
print("时间格式错误!")
except:
print("时间格式错误!请使用 HH:MM 格式")
elif choice == '4':
tool.cancel_shutdown()
elif choice == '5':
print("退出程序")
else:
print("无效的选择!")
if __name__ == "__main__":
main()
注意事项
权限问题:
- Windows 系统不需要特殊权限即可设置关机
- Linux/Mac 系统需要管理员权限(root 或 sudo)
安全性:
- 在生产环境中使用时请谨慎
- 确保有保存重要工作再关机
- 考虑添加确认对话框
兼容性:
- 不同系统使用不同的命令
- 测试代码时请小心,避免意外关机
取消关机:
- 每个方法都提供了取消关机的功能
- 记住取消命令以备不时之需
总结
本文介绍了四种 Python 设置定时关机的方法:
使用系统命令调用
使用 schedule 库定时执行
创建 GUI 界面工具
使用系统任务计划(高级)
选择哪种方法取决于你的具体需求。对于简单的定时关机,方法一就足够了;如果需要更复杂的定时逻辑,可以考虑使用 schedule 库;如果想要用户友好的界面,可以创建 GUI 工具。