杰瑞科技汇

Python Cheetah安装步骤是怎样的?

Cheetah 是一个老牌但功能强大的模板引擎,它的语法非常独特,借鉴了 Python 本身,使得模板逻辑清晰易懂。

什么是 Cheetah?

Cheetah 是一个 Python 编译的模板引擎,意味着它会将你的模板文件(.tmpl)编译成 Python 代码,然后执行这些代码来生成最终的文本输出(如 HTML、XML、邮件等)。

主要特点:

  • Pythonic 语法:模板中可以直接使用 Python 的表达式、循环 (for)、条件判断 (if/else) 等,非常直观。
  • 可重用:支持模板继承和宏(在 Cheetah 中称为 def blocks),方便构建大型、可维护的网站。
  • 性能较好:因为是编译执行的,所以比纯解释执行的模板引擎(如早期版本的 Jinja2)速度更快。
  • 独立运行:模板文件本身可以直接通过命令行执行,非常方便调试。

安装 Cheetah

安装 Cheetah 非常简单,推荐使用 pip

步骤 1:确保你有 Python 和 pip

确保你的系统已经安装了 Python 和包管理工具 pip,你可以在终端或命令行中运行以下命令来检查:

# 检查 Python 版本
python --version
# 或者 (如果系统有多个 Python 版本)
python3 --version
# 检查 pip 版本
pip --version
# 或者
pip3 --version

步骤 2:使用 pip 安装

打开你的终端(在 Windows 上是 Command Prompt 或 PowerShell,在 macOS/Linux 上是 Terminal),然后执行以下命令:

pip install Cheetah3

为什么是 Cheetah3

  • Cheetah 这个包名通常指向的是非常古老的 Cheetah 2.x 版本,它可能与 Python 3 不兼容。
  • Cheetah3 是专门为 Python 3 和现代 Python 生态设计的分支,是当前推荐的安装包。

安装完成后,你会看到类似 "Successfully installed Cheetah3-xxx" 的提示。


验证安装

安装完成后,你可以通过以下两种方式来验证 Cheetah 是否安装成功。

使用命令行工具

Cheetah 安装后提供了一个命令行工具 cheetah,你可以用它来编译和运行模板文件。

  1. 创建一个简单的模板文件,hello.tmpl

    #hello.tmpl
    #def greet(name)
    Hello, $name!
    #end def
    #for i in range(3):
    -- $greet('World') --
    #end for
  2. 在终端中,使用 cheetah 命令来编译并执行它:

    cheetah compile hello.tmpl

    这会在同目录下生成一个 hello.py 文件(这是编译后的 Python 代码)。

  3. 运行编译后的 Python 文件:

    python hello.py

    你应该会看到如下输出:

    -- Hello, World! --
    -- Hello, World! --
    -- Hello, World! --

在 Python 代码中导入

你也可以直接在 Python 脚本中导入并使用 Cheetah。

创建一个 test_cheetah.py 文件:

# test_cheetah.py
from Cheetah.Template import Template
# 定义模板字符串
template_string = """
#def greet(name)
Hello, $name!
#end def
The current year is $int(year).
"""
# 准备要传入模板的数据
context = {
    'year': 2025
}
# 创建模板实例
# searchList 参数是一个列表,Cheetah 会按顺序查找其中的变量和定义
t = Template(template_string, searchList=[context])
# 渲染模板并打印结果
print(t)

运行这个脚本:

python test_cheetah.py

输出结果将是:

Hello, !
The current year is 2025.

(注意:greet 函数被定义了但没有被调用,所以第一行只有 Hello,


Cheetah 基础语法示例

Cheetah 的语法非常直观,如果你懂 Python,上手会非常快。

变量替换

使用 符号来插入变量。

# hello.tmpl
Hello, $user!
Your balance is: $balance
from Cheetah.Template import Template
t = Template("Hello, $user!", searchList=[{'user': 'Alice'}])
print(t) # 输出: Hello, Alice!

语句块 (Statements)

使用 开头来写 Python 语句。

# for item in items:
* $item
#end for
from Cheetah.Template import Template
t = Template("#for i in range(3):$i#end for", searchList=[{}])
print(t) # 输出: 012

定义和调用宏 (Defining and Calling Macros)

使用 #def#end def 来定义可重用的代码块,然后通过 $macro_name 来调用。

#header.tmpl
<html>
<head><title>$title</title></head>
<body>
#def header_content
    <h1>Welcome to my site!</h1>
#end def
$header_content
</body>
</html>

模板继承

这是 Cheetah 的一个强大功能,你可以创建一个基础模板,然后在子模板中覆盖其特定部分。

  1. 创建基础模板 base.tmpl:

    #base.tmpl
    <html>
    <head><title>$title</title></head>
    <body>
    #def header
        <h1>Default Header</h1>
    #end def
    $header
    #def content
        <!-- Default content goes here -->
    #end def
    $content
    </body>
    </html>
  2. 创建子模板 page.tmpl:

    #page.tmpl
    #extends base.tmpl
    #set $title = "My Awesome Page"
    #def header
        <h1>This is my custom header!</h1>
    #end def
    #def content
        <p>This is the main content of my page.</p>
    #end def
  3. 编译和运行 page.tmpl:

    cheetah compile page.tmpl
    python page.py

    输出结果:

    <html>
    <head><title>My Awesome Page</title></head>
    <body>
        <h1>This is my custom header!</h1>
        <p>This is the main content of my page.</p>
    </body>
    </html>

常见问题与注意事项

  1. 安装 Cheetah 而不是 Cheetah3: 如果你遇到 ModuleNotFoundError: No module named 'Cheetah',很可能是因为你用 pip install Cheetah 安装了旧版本,请确保使用 pip install Cheetah3

  2. Python 2 vs Python 3: Cheetah3 是为 Python 3 设计的,如果你仍在使用 Python 2,你需要安装 pip install Cheetah(旧版)。但强烈建议你升级到 Python 3

  3. 与 Flask/Django 等框架集成: Cheetah 可以作为这些模板引擎的替代品,在 Flask 中,你可以这样配置:

    from flask import Flask, render_template_string
    from Cheetah.Template import Template
    app = Flask(__name__)
    @app.route('/')
    def index():
        template_content = """
        #def header
            <h1>My Flask App with Cheetah</h1>
        #end def
        $header
        Welcome to the homepage!
        """
        # 使用 Cheetah 的 render_template_string
        return render_template_string(template_content, searchList=[{}])
    if __name__ == '__main__':
        app.run()
步骤 命令/操作 描述
安装 pip install Cheetah3 推荐使用此命令安装 Python 3 兼容版。
验证 cheetah compile my_template.tmpl 使用命令行工具编译模板。
使用 python my_template.py 运行编译后的 Python 文件查看输出。
代码集成 from Cheetah.Template import Template 在 Python 脚本中导入并使用。

Cheetah 是一个功能强大且语法清晰的模板引擎,特别适合那些喜欢直接在模板中编写 Python 逻辑的开发者,希望这份指南能帮助你顺利安装和使用它!

分享:
扫描分享到社交APP
上一篇
下一篇