杰瑞科技汇

Python编译与构建有何区别?

Of course! "Python compile build" can mean a few different things, from compiling your Python code into a more efficient form to building a distributable package. Let's break it down into the most common scenarios.

Python编译与构建有何区别?-图1
(图片来源网络,侵删)

Scenario 1: Compiling a Single Python File (.py -> .pyc)

This is the most basic form of "compilation" in Python. When you run a Python script, the Python interpreter first translates your human-readable source code (.py file) into Python Bytecode, which is a lower-level, platform-independent set of instructions. This bytecode is then executed by the Python Virtual Machine (PVM).

The interpreter automatically saves this bytecode in a __pycache__ directory with a .pyc extension (e.g., my_script.cpython-39.pyc). The 39 refers to your Python version (3.9). The next time you run the script, Python will check if the source code has changed. If not, it can skip the compilation step and run the existing .pyc file, making startup faster.

How to Manually Compile a Single File

You can force this compilation using the py_compile module from the command line.

File: my_script.py

Python编译与构建有何区别?-图2
(图片来源网络,侵删)
import time
def main():
    print("Hello, World!")
    # Simulate some work
    time.sleep(2)
    print("Compilation is complete!")
if __name__ == "__main__":
    main()

Command:

# The -m flag runs a module as a script
python -m py_compile my_script.py

What happens:

  1. A new directory named __pycache__ will be created (if it doesn't exist).
  2. Inside, you'll find a file like my_script.cpython-311.pyc (the version number will match your Python installation).
  3. You can now run my_script.py and it will start a bit faster on the first run after compilation.

Why do this?

  • Startup Speed: For very large scripts or applications, this can slightly reduce startup time.
  • Obfuscation: The .pyc file is not human-readable, so it can be a very basic way to hide your source code logic. (Note: This is not secure and can be easily decompiled).

Scenario 2: Compiling a Package of Python Files

If you have a project with multiple Python files (a package), you want to compile all of them at once. The compileall module is perfect for this.

Python编译与构建有何区别?-图3
(图片来源网络,侵删)

Project Structure:

my_project/
├── __init__.py
├── utils.py
└── main.py

Command:

# Compile all .py files in the 'my_project' directory and its subdirectories
python -m compileall my_project

What happens:

  • compileall will traverse the my_project directory.
  • It will compile main.py and utils.py into their respective .pyc files inside my_project/__pycache__/.
  • It will also compile __init__.py (if it exists) into __pycache__/__init__.cpython-311.pyc.

Scenario 3: Building a Distributable Package (The "Real" Build)

This is what most people mean when they talk about "building" a Python project. The goal is to create a distributable archive (a .whl wheel file or a .tar.gz source archive) that can be easily installed by others using pip.

This process uses a modern standard called PEP 517. The core of this standard is a pyproject.toml file that describes your project and how to build it.

Step-by-Step Guide to Building a Package

Let's create a simple project called my_calculator.

Project Structure:

my_calculator_project/
├── src/
│   └── my_calculator/
│       ├── __init__.py
│       └── operations.py
├── pyproject.toml
└── README.md

Write the Code:

  • src/my_calculator/__init__.py (Makes it a package)

    from .operations import add, subtract
    __version__ = "0.1.0"
  • src/my_calculator/operations.py (The actual code)

    def add(a, b):
        return a + b
    def subtract(a, b):
        return a - b

Create pyproject.toml (The Build Configuration) This is the most important file for modern Python packaging.

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "my-calculator"
version = "0.1.0"
authors = [
  { name="Your Name", email="you@example.com" },
]
description = "A simple calculator package"
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]
[project.urls]
Homepage = "https://github.com/your-username/my-calculator"
Issues = "https://github.com/your-username/my-calculator/issues"

Install Build Tools You need a "build frontend" to read the pyproject.toml and orchestrate the build. build is the standard tool.

pip install build

Run the Build Command Navigate to your project's root directory (my_calculator_project/) in your terminal and run:

python -m build

What happens:

  • The build tool will read your pyproject.toml.
  • It will execute the build backend (setuptools) to create the package.
  • You will see output like this:
    * Creating virtualenv isolated environment...
    * Installing packages in isolated environment... (setuptools, wheel)
    * Getting build dependencies for wheel...
    * Installing backend dependencies ... done
    * Preparing wheel build...
    * Building wheel for my_calculator (pyproject.toml) ... done
    * Successfully built my_calculator-0.1.0-py3-none-any.whl
  • A new dist/ directory will be created containing your distributable files:
    my_calculator_project/
    ├── dist/
    │   ├── my_calculator-0.1.0-py3-none-any.whl  # The Wheel file (preferred)
    │   └── my_calculator-0.1.0.tar.gz            # The source archive
    ├── pyproject.toml
    └── src/

Install and Test Your Package You can now install your newly built package directly from the dist directory!

# Install the wheel file
pip install dist/my_calculator-0.1.0-py3-none-any.whl
# Now you can use it anywhere in your Python environment
python -c "import my_calculator; print(my_calculator.add(5, 3))"
# Output: 8

Scenario 4: Compiling to a Binary (e.g., with PyInstaller or Nuitka)

Sometimes, you want to distribute a Python application to users who don't have Python installed. For this, you use a tool like PyInstaller or Nuitka to compile your entire application and its dependencies into a single executable file (.exe on Windows, an executable binary on macOS/Linux).

Using PyInstaller (Example):

Install PyInstaller:

pip install pyinstaller

Create a simple script: app.py

import time
from my_calculator import add # Using our package from before
def main():
    print("Welcome to the Awesome Calculator App!")
    result = add(10, 5)
    print(f"The result of 10 + 5 is: {result}")
    time.sleep(5) # Keep window open for 5 seconds
    print("App closing...")
if __name__ == "__main__":
    main()

Build the executable:

# The --onefile flag bundles everything into a single executable
pyinstaller --onefile app.py

What happens:

  • PyInstaller will analyze your script and all its dependencies.
  • It will create a dist/ directory.
  • Inside dist/, you'll find a single executable file named app (or app.exe on Windows).
  • You can now run this file on any machine with the same operating system and architecture, even if it doesn't have Python installed.

Summary: Which One Do You Need?

Goal Tool/Method Output
Speed up script startup python -m py_compile <file> .pyc files in __pycache__
Compile a whole package `python -
分享:
扫描分享到社交APP
上一篇
下一篇