我的知识记录

Python 开机自启脚本设置:Windows 启动项与 Linux systemd

Python 脚本设置开机自启动,Windows 用启动文件夹和注册表、Linux 用 systemd 服务、Mac 用 LaunchAgent,配合 nohup 实现无人值守常驻运行。

场景痛点

写好一个定时任务或监控脚本,每次开机都要手动打开终端跑一遍,重启电脑就忘了。把脚本加进开机自启,开机后自动在后台运行,不用人管,才是真正的"无人值守自动化"。本文给出 Windows、Linux、Mac 三种系统的标准做法。

用到的库

无第三方依赖,纯系统配置。脚本本身用 time.sleep 做常驻循环即可。

完整代码

import time
import logging
from datetime import datetime


# 常驻示例:每 10 秒打印一次心跳
logging.basicConfig(
filename="autostart_demo.log",
level=logging.INFO,
format="%(asctime)s %(message)s",
)


def heartbeat():
logging.info("脚本还活着,当前时间 %s", datetime.now())


def main():
logging.info("=== 脚本启动 ===")
while True:
try:
heartbeat()
except Exception as e:
logging.exception("任务出错:%s", e)
time.sleep(10)


if __name__ == "__main__":
main()

代码讲解

  • 这是一个常驻脚本模板:while True + time.sleep(10) 每 10 秒执行一次业务逻辑,try/except 兜住异常防止整段崩掉。
  • logging 写文件而不是 print,因为开机自启后没有终端,print 输出看不到。
  • 日志文件 autostart_demo.log 就是排错第一现场,开机后不工作先看它。

Windows:放进启动文件夹

  1. Win+R,输入 shell:startup 回车,打开"启动"文件夹。
  2. 在文件夹里新建一个 start.bat,内容:
@echo off
cd /d D:\scripts
start /b pythonw.exe autostart_demo.py
  • pythonw.exe 是无窗口版本,不会黑框框。
  • start /b 后台运行。 3. 重启电脑,脚本自动在后台启动,日志写到 D:\scripts\autostart_demo.log

Windows:注册成计划任务(推荐)

  1. 打开"任务计划程序",创建任务。
  2. 触发器选"登录时"。
  3. 操作选"启动程序",程序填 pythonw.exe,参数填完整脚本路径。
  4. 勾选"不管用户是否登录都要运行",更稳定。

Linux:systemd 服务

新建 /etc/systemd/system/pyautostart.service

[Unit]
Description=Python Autostart Demo
After=network.target

[Service]
User=youruser
WorkingDirectory=/home/youruser/scripts
ExecStart=/usr/bin/python3 /home/youruser/scripts/autostart_demo.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

然后:

sudo systemctl daemon-reload
sudo systemctl enable pyautostart
sudo systemctl start pyautostart
systemctl status pyautostart

Restart=always 表示脚本崩了 5 秒后自动重启,比裸 nohup 稳得多。

Mac:LaunchAgent

新建 ~/Library/LaunchAgents/com.demo.autostart.plist,内容指向脚本路径,然后:

launchctl load ~/Library/LaunchAgents/com.demo.autostart.plist

运行结果

配置完重启电脑: - Windows:登录后右下角看不到任何窗口,但 autostart_demo.log 里每 10 秒多一行。 - Linux:systemctl status pyautostart 显示 active (running)journalctl -u pyautostart -f 实时看日志。 - Mac:登录后后台自动跑。

注意事项

  • 路径一律写绝对路径:开机自启时工作目录不是你想的那个,相对路径会找不到文件。
  • Python 解释器路径也要绝对,Windows 用 where python 查,Linux 用 which python3
  • Windows 用 pythonw.exe 而不是 python.exe,否则每次开机都弹黑框。
  • 脚本里如果依赖虚拟环境,ExecStart 要写虚拟环境里的 python 绝对路径。
  • 先手动跑通脚本再加自启,别直接塞进去重启找问题,效率极低。
  • 自启脚本出问题第一时间看日志文件,别靠猜。

Python 开机自启脚本设置:Windows 启动项与 Linux systemd

标签:

更新时间:2026-09-14 20:45:46

上一篇:Python 批量压缩图片体积:在清晰度和大小之间找平衡

下一篇:Python抓取网页链接批量提取:正则与BeautifulSoup两种方案