Python开机自启案例如何设置脚本自启

wen python案例 23

本文目录导读:

Python开机自启案例如何设置脚本自启

  1. Windows 系统
  2. Linux 系统
  3. 实用的自启脚本模板
  4. 最佳实践建议
  5. 注意事项

我来介绍几种在Windows和Linux系统下设置Python脚本开机自启的方法。

Windows 系统

方法1:添加到启动文件夹(最简单)

  1. 创建批处理文件 (start_script.bat)

    @echo off
    python C:\path\to\your\script.py
  2. 放入启动文件夹

  • Win + R,输入 shell:startup
  • 将批处理文件复制到打开的文件夹

方法2:任务计划程序(推荐)

# 创建任务计划的Python代码示例
import subprocess
import os
def create_task():
    """创建Windows任务计划"""
    script_path = r"C:\path\to\your\script.py"
    python_path = r"C:\Python39\python.exe"
    task_name = "MyPythonScript"
    cmd = f'''
    schtasks /create /tn "{task_name}" /tr "{python_path} {script_path}" /sc onstart /ru SYSTEM /f
    '''
    subprocess.run(cmd, shell=True)
    print(f"任务 {task_name} 创建成功")
if __name__ == "__main__":
    create_task()

方法3:注册表启动

import winreg
import os
def add_to_registry():
    """添加到注册表启动项"""
    script_path = r"C:\path\to\your\script.py"
    python_path = r"C:\Python39\python.exe"
    key_name = "MyPythonScript"
    # 打开注册表键
    key = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        r"Software\Microsoft\Windows\CurrentVersion\Run",
        0, winreg.KEY_SET_VALUE
    )
    # 设置启动项
    winreg.SetValueEx(key, key_name, 0, winreg.REG_SZ, 
                     f'"{python_path}" "{script_path}"')
    winreg.CloseKey(key)
    print("已添加到注册表启动项")
# 删除注册表项
def remove_from_registry():
    key_name = "MyPythonScript"
    key = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        r"Software\Microsoft\Windows\CurrentVersion\Run",
        0, winreg.KEY_SET_VALUE
    )
    winreg.DeleteValue(key, key_name)
    winreg.CloseKey(key)
if __name__ == "__main__":
    add_to_registry()

Linux 系统

方法1:systemd 服务(推荐)

  1. 创建服务文件 (/etc/systemd/system/myscript.service)
    [Unit]
    Description=My Python Script
    After=network.target

[Service] Type=simple User=yourusername WorkingDirectory=/path/to/script ExecStart=/usr/bin/python3 /path/to/script.py Restart=on-failure RestartSec=10

[Install] WantedBy=multi-user.target


2. **启用并启动服务**
```bash
sudo systemctl daemon-reload
sudo systemctl enable myscript.service
sudo systemctl start myscript.service

方法2:crontab(定时任务)

# 编辑crontab
crontab -e
# 添加开机自启(@reboot)
@reboot python3 /path/to/script.py >> /path/to/log.txt 2>&1
# 或者延迟启动
@reboot sleep 30 && python3 /path/to/script.py

方法3:rc.local(传统方式)

  1. 编辑rc.local

    sudo nano /etc/rc.local
  2. 添加脚本

    #!/bin/sh
    # 在exit 0之前添加
    python3 /path/to/script.py &
    exit 0
  3. 设置执行权限

    sudo chmod +x /etc/rc.local

实用的自启脚本模板

带日志记录的自启脚本

#!/usr/bin/env python3
"""
带日志记录的自启脚本模板
"""
import os
import sys
import logging
from datetime import datetime
# 配置日志
log_file = os.path.expanduser("~/.myscript/script.log")
os.makedirs(os.path.dirname(log_file), exist_ok=True)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_file),
        logging.StreamHandler()
    ]
)
def main():
    """主函数"""
    logging.info("脚本启动成功")
    # 你的业务逻辑
    try:
        # 示例:监控某个文件
        watch_file = "/path/to/watch.txt"
        if os.path.exists(watch_file):
            logging.info(f"监控文件存在: {watch_file}")
        else:
            logging.warning(f"监控文件不存在: {watch_file}")
        # 保持运行
        while True:
            # 你的循环任务
            pass
    except KeyboardInterrupt:
        logging.info("脚本被手动停止")
    except Exception as e:
        logging.error(f"运行错误: {e}")
        sys.exit(1)
if __name__ == "__main__":
    main()

最佳实践建议

检查是否已运行(防止重复启动)

import os
import sys
import atexit
import fcntl
def check_single_instance():
    """检查是否只有一个实例运行"""
    lock_file = "/tmp/myscript.lock"
    try:
        fd = os.open(lock_file, os.O_CREAT | os.O_RDWR)
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print("脚本已在运行中")
        sys.exit(0)
    # 程序退出时释放锁
    atexit.register(lambda: os.close(fd))
# 在main之前调用
check_single_instance()

自启安装脚本

#!/usr/bin/env python3
"""
一键安装自启脚本
支持 Windows 和 Linux
"""
import os
import platform
def install_autostart():
    """安装自启"""
    system = platform.system()
    if system == "Windows":
        # Windows 实现
        pass
    elif system == "Linux":
        # Linux systemd 实现
        service_content = f"""[Unit]
Description=My Python Script
After=network.target
[Service]
Type=simple
User={os.getlogin()}
WorkingDirectory={os.getcwd()}
ExecStart={sys.executable} {os.path.abspath(__file__)}
Restart=on-failure
[Install]
WantedBy=multi-user.target
"""
        service_path = "/etc/systemd/system/myscript.service"
        # 写入服务文件
        with open("/tmp/myscript.service", "w") as f:
            f.write(service_content)
        # 安装服务
        os.system("sudo cp /tmp/myscript.service /etc/systemd/system/")
        os.system("sudo systemctl daemon-reload")
        os.system("sudo systemctl enable myscript.service")
        print("自启安装成功!")
if __name__ == "__main__":
    install_autostart()

调试建议

# Windows 下查看启动日志
# 在脚本中添加文件日志记录
# Linux 下查看服务状态
sudo systemctl status myscript.service
sudo journalctl -u myscript.service -f
# 查看实时日志
tail -f /path/to/script.log

注意事项

  1. 路径问题:脚本中使用绝对路径,不要依赖相对路径
  2. 环境变量:确保Python解释器路径正确
  3. 权限问题:Linux下可能需要sudo权限
  4. 依赖检查:确保所有依赖已安装
  5. 错误处理:添加适当的异常处理和日志记录
  6. 资源占用:避免脚本占用过多系统资源

选择哪种方法取决于你的具体需求和操作系统,对于生产环境,推荐使用systemd(Linux)或任务计划程序(Windows),因为它们提供了更好的控制和管理功能。

抱歉,评论功能暂时关闭!