Windows 添加自定义服务实现开机(用户登录之前)自动运行 Python 脚本

实现效果

使用 Python 编写的一个脚本, 希望在 Windows 系统启动时, 用户登录之前就自动运行.

准备工作

首先确保 Python 脚本可以手动正常运行, 演示起见, 编写下面的一个简单的脚本用于在 C 盘根目录中生成一个包含脚本运行时间戳的文本文件. Python 脚本存放在 C:\Python_Scripts\demo.py, 内容如下:

python 复制代码
from datetime import datetime

if __name__ == "__main__":
    with open("c:/result.txt", "w", encoding="utf8") as file:
        file.write(f"{datetime.now()}")

    print("Script finished.")

手动运行测试正常:

创建自定义 Windows 服务

之前手动执行脚本时直接运行了 python, Windows 会自动从系统环境变量的 PATH 去寻找对应的可执行程序, 做成服务的时候, 最好还是用可执行程序的完整绝对路径, 例如: C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe. 如果是 Virtual Environment (venv) 的 Python 环境, 那就自己从资源管理器里面找到对应路径手动拼出来吧. 以管理员身份打开 PowerShell:

powershell 复制代码
# 配置要执行的动作
$action = New-ScheduledTaskAction -Execute "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe" -Argument "C:\Python_Scripts\demo.py"

# 配置触发规则, 每次系统启动时
$trigger = New-ScheduledTaskTrigger -AtStartup

# 配置任务将会以 Administrator 账户身份运行, 实现无需等到用户登录之后再触发
$principal = New-ScheduledTaskPrincipal -LogonType S4U -UserId "Administrator"

# 注册计划任务
Register-ScheduledTask -Action $action -Trigger $trigger -Principal $principal -TaskName "My task at system startup." -Description "This task should start before user log on."

测试

关闭 Windows 系统后再次启动, 等待几分钟后再使用 RDP 远程登录, 检查 C: 盘根目录下面成功生成了 result.txt 文件, 检查文件内容记录的时间戳, 比当前登录的时间要早几分钟, 表明确实是在系统启动的时候就自动执行了, 而不是用户登录后才触发.

相关推荐
aqi002 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn3 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵20 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent