定时关机python
时间: 2025-01-03 18:41:57 浏览: 13
### 使用 Python 实现定时关机功能
对于 Windows 和 Linux 系统,可以分别采用不同的方法来创建一个能够定时关闭计算机的 Python 脚本。
#### 对于 Windows:
在 Windows 上,`os.system()` 函数可用于调用命令行指令 `shutdown /s /t 秒数` 来安排系统的关闭时间。下面是一个简单的例子:
```python
import os
import time
def shutdown_windows(seconds=60):
"""Schedule a shutdown on Windows."""
# Convert seconds into string format required by command line.
wait_time = str(int(seconds))
# Call the OS-specific shutdown command with delay argument.
os.system(f'shutdown /s /t {wait_time}')
if __name__ == "__main__":
# Set up timer before initiating shutdown process.
print("Shutting down in one minute...")
time.sleep(59) # Sleep for almost a full minute minus one second
# Execute scheduled shutdown.
shutdown_windows()
```
此代码将在大约一分钟后触发Windows 的关机流程[^1]。
#### 对于 Linux:
Linux 中同样利用 `os.system()` 或者更推荐的方式是使用 subprocess 模块去执行 shell 命令 `shutdown -h +分钟数`. 下面给出一段适用于大多数基于 Unix 的操作系统的 Python 代码片段:
```python
import subprocess
from datetime import timedelta
from dateutil.parser import parse
def schedule_shutdown_linux(shutdown_in_minutes=1):
"""Schedules a system shutdown at specified minutes from now"""
current_time = parse(subprocess.check_output(['date']).decode().strip())
target_time = (current_time + timedelta(minutes=int(shutdown_in_minutes))).strftime('%H:%M')
try:
result = subprocess.run(
['sudo', 'shutdown', '-h', f'+{int(shutdown_in_minutes)}'],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
message = "Shutdown has been successfully scheduled."
output = result.stdout.decode('utf-8').splitlines()[-1].replace('\n', '')
if output != "":
message += "\nOutput: "+output
return {"status": True, "message": message}
except Exception as e:
error_msg = str(e).replace("\n", "")
return {"status": False, "error": f"Failed to schedule shutdown.{error_msg}"}
if __name__ == '__main__':
response = schedule_shutdown_linux()
if not response["status"]:
raise RuntimeError(response['error'])
else:
print(response['message'])
```
这段程序会计算当前时间和目标时间之间的差异,并据此设定关机计划。它还处理了权限提升的需求以及可能发生的异常情况[^3].
阅读全文