You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动安装最新版Quarto 实现博客渲染前自动更新

Python环境下Quarto渲染前自动更新最新版本实现方案

实现思路

把Quarto版本校验、更新逻辑和博客渲染逻辑绑定到同一个执行入口,每次启动渲染流程前自动完成版本检查,本地未安装Quarto或版本低于最新稳定版时自动完成静默安装,全程无需人工操作。

前置依赖

先安装两个第三方依赖库,其余功能直接调用Python标准库即可:

pip install requests packaging

完整实现代码

import os
import platform
import subprocess
import sys
import tempfile
import requests
from packaging.version import Version

def get_local_quarto_version() -> Version | None:
    """获取本地已安装的Quarto版本"""
    try:
        res = subprocess.run(
            ["quarto", "--version"],
            capture_output=True,
            text=True,
            check=True
        )
        return Version(res.stdout.strip())
    except (subprocess.CalledProcessError, FileNotFoundError):
        # 本地未安装Quarto时返回None,直接走全量安装流程
        return None

def get_latest_quarto_version() -> Version:
    """获取Quarto最新稳定版版本号"""
    # 替换为Quarto官方最新版本查询接口地址
    resp = requests.get("替换为Quarto官方版本查询接口地址", timeout=10)
    resp.raise_for_status()
    version_str = resp.json()["version"]
    return Version(version_str)

def download_and_install_latest(version: Version):
    """根据当前系统类型、架构下载对应安装包并执行静默安装"""
    sys_name = platform.system().lower()
    arch = platform.machine().lower()
    # 匹配系统和架构对应的安装包格式、静默安装命令
    if sys_name == "windows":
        pkg_suffix = "win-x64.msi" if "64" in arch and "arm" not in arch else "win-arm64.msi"
        install_cmd = ["msiexec", "/i", "{installer_path}", "/qn", "/norestart"]
    elif sys_name == "darwin":
        pkg_suffix = "macos-x86_64.pkg" if "x86" in arch else "macos-arm64.pkg"
        install_cmd = ["sudo", "installer", "-pkg", "{installer_path}", "-target", "/"]
    else:
        # Linux环境可根据自身发行版替换为rpm包安装命令
        pkg_suffix = "linux-amd64.deb" if "x86" in arch or "amd" in arch else "linux-arm64.deb"
        install_cmd = ["sudo", "dpkg", "-i", "{installer_path}"]
    
    # 替换为Quarto官方安装包下载根路径
    pkg_url = f"替换为Quarto官方安装包下载根路径/{version}/{pkg_suffix}"
    with tempfile.TemporaryDirectory() as tmp_dir:
        pkg_path = os.path.join(tmp_dir, pkg_suffix.split("/")[-1])
        # 流式下载安装包到临时目录,避免占用多余磁盘空间
        with requests.get(pkg_url, stream=True, timeout=60) as r:
            r.raise_for_status()
            with open(pkg_path, "wb") as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)
        # 替换安装命令中的路径占位符,执行无交互安装
        install_cmd = [cmd.format(installer_path=pkg_path) for cmd in install_cmd]
        subprocess.run(install_cmd, check=True)

def render_blog():
    """原有Quarto博客渲染逻辑,可根据自身项目参数调整命令"""
    subprocess.run(["quarto", "render"], check=True)

if __name__ == "__main__":
    local_ver = get_local_quarto_version()
    latest_ver = get_latest_quarto_version()
    if local_ver is None or local_ver < latest_ver:
        print(f"检测到Quarto版本变动,本地版本:{local_ver},最新稳定版:{latest_ver},开始自动安装...")
        download_and_install_latest(latest_ver)
        # 安装完成后二次校验版本,确认更新成功
        new_local_ver = get_local_quarto_version()
        if new_local_ver != latest_ver:
            print("Quarto更新失败,请检查执行权限或网络连接")
            sys.exit(1)
        print(f"Quarto已成功更新到版本{latest_ver}")
    else:
        print(f"Quarto已是最新版本{local_ver},跳过更新步骤")
    # 版本校验通过后执行渲染
    print("开始渲染博客内容...")
    render_blog()

注意事项

  • 自动安装需要对应系统权限:Linux/macOS下执行脚本的用户需要配置安装命令的免密sudo权限,否则安装步骤会卡在密码输入环节;Windows下需要用管理员身份运行脚本。
  • 若担心新版本存在兼容性bug,可以在版本拉取逻辑中增加判断规则:只更新发布超过7天的正式版,避开刚发布的未修复问题版本。
  • 如果是在CI/CD环境运行博客构建,直接把这个脚本作为构建步骤的入口即可,不需要提前在构建镜像中预装Quarto,脚本会自动完成安装、更新、渲染全流程。

内容的提问来源于stack exchange,提问作者Lucas A. Meyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:57:15