znlgis 博客

GIS开发与技术分享

第2章:安装与环境配置

正确的安装和环境配置是使用 Shapely 的第一步。本章将详细介绍 Shapely 在不同操作系统和环境下的安装方法、GEOS 依赖管理、虚拟环境配置、Docker 部署,以及常见安装问题的排查与解决。


2.1 系统要求

2.1.1 Python 版本要求

Shapely 2.0+ 要求 Python 3.8 或更高版本。建议使用 Python 3.10+ 以获得最佳性能和兼容性。

Shapely 版本 最低 Python 版本 推荐 Python 版本
1.7.x Python 2.7 / 3.5+ Python 3.7
1.8.x Python 3.6+ Python 3.8
2.0.x Python 3.8+ Python 3.10+

2.1.2 操作系统支持

Shapely 支持三大主流操作系统:

操作系统 支持状态 预编译 Wheel
Windows(x64) ✅ 完全支持 ✅ 提供
macOS(Intel/Apple Silicon) ✅ 完全支持 ✅ 提供
Linux(x64/ARM64) ✅ 完全支持 ✅ 提供(manylinux)

2.1.3 GEOS 依赖

Shapely 依赖 GEOS(Geometry Engine - Open Source)作为底层几何计算引擎:

  • Shapely 2.0+ 需要 GEOS 3.10 或更高版本
  • 通过 pip 安装时,预编译的 wheel 包已内置 GEOS,无需单独安装
  • 从源码编译时,需要系统预装 GEOS 开发库

2.2 pip 安装(推荐)

2.2.1 基本安装

使用 pip 是安装 Shapely 最简单的方式,预编译的 wheel 包已包含 GEOS 库:

# 安装最新版本
pip install shapely

# 安装指定版本
pip install shapely==2.0.6

# 升级到最新版本
pip install --upgrade shapely

2.2.2 安装过程说明

当使用 pip 安装时,pip 会自动从 PyPI 下载预编译的 wheel 包:

$ pip install shapely
Collecting shapely
  Downloading shapely-2.0.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.5 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.5/2.5 MB 5.2 MB/s eta 0:00:00
Collecting numpy>=1.14 (from shapely)
  Using cached numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (18.3 MB)
Installing collected packages: numpy, shapely
Successfully installed numpy-1.26.4 shapely-2.0.6

预编译的 wheel 包特点:

  • 包含 GEOS:不需要系统预装 GEOS
  • 平台特定:针对不同操作系统和 CPU 架构编译
  • 即装即用:无需编译步骤,安装速度快

2.2.3 验证安装

# 验证 Shapely 安装
import shapely
print(f"Shapely 版本: {shapely.__version__}")
print(f"GEOS 版本: {shapely.geos_version}")
print(f"GEOS C API 版本: {shapely.geos_capi_version}")

# 简单功能测试
from shapely import Point
p = Point(1, 2)
print(f"测试点: {p}")
print(f"缓冲区面积: {p.buffer(1).area:.4f}")

# 预期输出:
# Shapely 版本: 2.0.6
# GEOS 版本: (3, 11, 2)
# GEOS C API 版本: (1, 18, 2)
# 测试点: POINT (1 2)
# 缓冲区面积: 3.1365

2.3 conda 安装

2.3.1 使用 conda-forge

如果你使用 Anaconda 或 Miniconda,推荐从 conda-forge 频道安装:

# 从 conda-forge 安装
conda install -c conda-forge shapely

# 指定版本
conda install -c conda-forge shapely=2.0.6

# 创建新环境并安装
conda create -n gis-env python=3.11 shapely -c conda-forge
conda activate gis-env

2.3.2 conda vs pip 的选择

安装方式 优点 缺点
pip 版本更新快,安装简单 可能与 conda 环境冲突
conda 依赖管理更完善,与其他 GIS 库兼容好 版本更新可能滞后

建议:如果你同时使用多个 GIS 库(GeoPandas、Fiona、GDAL),推荐使用 conda 统一管理依赖。

2.3.3 一站式 GIS 环境

# 创建完整的 GIS 开发环境
conda create -n geo-analysis python=3.11 \
    shapely \
    geopandas \
    fiona \
    pyproj \
    matplotlib \
    jupyterlab \
    -c conda-forge

conda activate geo-analysis

2.4 从源码编译安装

2.4.1 适用场景

在以下情况下,你可能需要从源码编译安装:

  • 需要使用特定版本的 GEOS
  • 平台没有预编译的 wheel(如某些 ARM 架构)
  • 需要调试或修改 Shapely 源码
  • 需要启用特定的编译选项

2.4.2 安装 GEOS 开发库

Ubuntu / Debian:

# 安装 GEOS 开发库
sudo apt-get update
sudo apt-get install libgeos-dev

# 验证安装
geos-config --version
# 3.10.2

CentOS / RHEL / Fedora:

# CentOS / RHEL
sudo yum install geos-devel

# Fedora
sudo dnf install geos-devel

macOS(Homebrew):

brew install geos
geos-config --version

Windows:

在 Windows 上从源码编译较为复杂,建议使用 OSGeo4W 安装 GEOS,或者直接使用预编译的 wheel。

2.4.3 编译安装步骤

# 1. 安装编译依赖
pip install numpy cython

# 2. 克隆源码
git clone https://github.com/shapely/shapely.git
cd shapely

# 3. 编译安装
pip install -e .

# 或者使用 build 工具
pip install build
python -m build
pip install dist/shapely-*.whl

2.4.4 指定 GEOS 路径

如果 GEOS 安装在非标准路径,需要设置环境变量:

# Linux / macOS
export GEOS_CONFIG=/usr/local/bin/geos-config
pip install shapely --no-binary shapely

# 或者指定 GEOS 库路径
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
export GEOS_INCLUDE_PATH=/usr/local/include
export GEOS_LIBRARY_PATH=/usr/local/lib

2.5 GEOS 依赖管理

2.5.1 检查 GEOS 版本

import shapely

# GEOS 版本(主版本, 次版本, 补丁版本)
print(f"GEOS 版本: {shapely.geos_version}")
# (3, 11, 2)

# GEOS C API 版本
print(f"GEOS C API 版本: {shapely.geos_capi_version}")
# (1, 18, 2)

# 格式化显示
major, minor, patch = shapely.geos_version
print(f"GEOS {major}.{minor}.{patch}")
# GEOS 3.11.2

2.5.2 GEOS 版本与功能对应

GEOS 版本 新增功能 Shapely 最低要求
3.10 CoverageUnion, 改进的 buffer Shapely 2.0
3.11 改进的 Voronoi 图,concave hull Shapely 2.0.2+
3.12 改进的 overlay 操作 Shapely 2.0.4+

2.5.3 确认 GEOS 库路径

import shapely.lib

# 查看 Shapely 绑定的 GEOS 共享库位置
print(shapely.lib.__file__)
# /path/to/site-packages/shapely/lib.cpython-311-x86_64-linux-gnu.so
# Linux 上查看链接的 GEOS 库
ldd $(python -c "import shapely.lib; print(shapely.lib.__file__)") | grep geos
# libgeos.so.3.11.2 => /usr/local/lib/libgeos.so.3.11.2

# macOS 上查看
otool -L $(python -c "import shapely.lib; print(shapely.lib.__file__)") | grep geos

2.6 虚拟环境配置

2.6.1 使用 venv

# 创建虚拟环境
python -m venv shapely-env

# 激活虚拟环境
# Linux / macOS
source shapely-env/bin/activate
# Windows
shapely-env\Scripts\activate

# 安装 Shapely
pip install shapely

# 验证
python -c "import shapely; print(shapely.__version__)"

# 退出虚拟环境
deactivate

2.6.2 使用 conda env

# 创建 conda 环境
conda create -n shapely-env python=3.11
conda activate shapely-env

# 安装 Shapely 及常用依赖
conda install -c conda-forge shapely numpy matplotlib

# 导出环境
conda env export > environment.yml

# 从文件重建环境
conda env create -f environment.yml

environment.yml 示例:

name: shapely-env
channels:
  - conda-forge
  - defaults
dependencies:
  - python=3.11
  - shapely=2.0.6
  - numpy
  - matplotlib
  - jupyterlab
  - pip:
    - some-pip-only-package

2.6.3 使用 Poetry

# 初始化项目
poetry init

# 添加 Shapely 依赖
poetry add shapely

# 添加开发依赖
poetry add --group dev pytest matplotlib

# 进入虚拟环境
poetry shell

# 运行脚本
poetry run python my_script.py

pyproject.toml 示例:

[tool.poetry]
name = "my-gis-project"
version = "0.1.0"
description = "GIS analysis project"

[tool.poetry.dependencies]
python = "^3.10"
shapely = "^2.0"
numpy = "^1.24"

[tool.poetry.group.dev.dependencies]
pytest = "^7.0"
matplotlib = "^3.7"

2.7 Docker 环境配置

2.7.1 基础 Dockerfile

FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 安装 Shapely(预编译 wheel 已包含 GEOS)
RUN pip install --no-cache-dir shapely numpy

# 复制应用代码
COPY . .

# 验证安装
RUN python -c "import shapely; print(f'Shapely {shapely.__version__}, GEOS {shapely.geos_version}')"

CMD ["python", "app.py"]

2.7.2 完整 GIS 环境 Dockerfile

FROM python:3.11-slim

WORKDIR /app

# 安装系统依赖(用于 Fiona 和 GDAL)
RUN apt-get update && apt-get install -y \
    libgdal-dev \
    libgeos-dev \
    libproj-dev \
    && rm -rf /var/lib/apt/lists/*

# 安装 Python GIS 库
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["python", "app.py"]

对应的 requirements.txt:

shapely>=2.0
numpy>=1.24
geopandas>=0.14
fiona>=1.9
pyproj>=3.6
matplotlib>=3.7

2.7.3 使用 conda 的 Docker 环境

FROM continuumio/miniconda3:latest

WORKDIR /app

# 使用 conda 安装 GIS 环境
RUN conda install -c conda-forge -y \
    python=3.11 \
    shapely \
    geopandas \
    fiona \
    pyproj \
    && conda clean -afy

COPY . .

CMD ["python", "app.py"]

2.7.4 docker-compose 配置

version: '3.8'
services:
  gis-app:
    build: .
    volumes:
      - ./data:/app/data
      - ./output:/app/output
    environment:
      - PYTHONUNBUFFERED=1

2.8 常见安装问题与解决方案

2.8.1 GEOS 库找不到

错误信息:

OSError: Could not find lib geos_c or load any of its variants

解决方案:

# 方案 1:确保安装了预编译的 wheel(推荐)
pip install shapely --force-reinstall

# 方案 2:安装 GEOS 开发库
# Ubuntu/Debian
sudo apt-get install libgeos-dev

# macOS
brew install geos

# 方案 3:设置 GEOS 库路径
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

2.8.2 版本冲突

错误信息:

ImportError: shapely.geos_version mismatch: expected (3, 11, 0), got (3, 8, 1)

解决方案:

# 完全卸载后重装
pip uninstall shapely -y
pip install shapely --no-cache-dir --force-reinstall

# 如果使用 conda,确保不混用 pip 和 conda
conda install -c conda-forge shapely --force-reinstall

2.8.3 Wheel 不匹配

错误信息:

ERROR: No matching distribution found for shapely

解决方案:

# 升级 pip
pip install --upgrade pip

# 检查 Python 版本和平台
python --version
python -c "import platform; print(platform.machine())"

# 如果没有预编译 wheel,从源码安装
pip install shapely --no-binary shapely

2.8.4 NumPy 版本不兼容

错误信息:

ImportError: numpy.core.multiarray failed to import

解决方案:

# 升级 NumPy
pip install --upgrade numpy

# 或者重新安装兼容版本
pip install "numpy>=1.20,<2.0" shapely

2.8.5 Shapely 1.x 到 2.0 的迁移问题

# 1.x 的导入方式(仍然兼容)
from shapely.geometry import Point, Polygon

# 2.0 推荐的导入方式
from shapely import Point, Polygon

# 检查是否是 2.0+
import shapely
major = int(shapely.__version__.split('.')[0])
if major >= 2:
    print("使用 Shapely 2.0+ 新特性")
else:
    print("旧版本,部分功能不可用")

2.9 IDE 配置建议

2.9.1 VSCode 配置

推荐扩展:

  • Python(ms-python.python):Python 语言支持
  • Pylance(ms-python.vscode-pylance):高级类型检查和智能提示
  • Jupyter(ms-toolsai.jupyter):Notebook 支持

settings.json 配置:

{
    "python.defaultInterpreterPath": "./shapely-env/bin/python",
    "python.analysis.typeCheckingMode": "basic",
    "python.analysis.autoImportCompletions": true,
    "python.analysis.extraPaths": [],
    "[python]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "ms-python.black-formatter"
    }
}

2.9.2 PyCharm 配置

  1. 设置 Python 解释器:File → Settings → Project → Python Interpreter
    • 选择包含 Shapely 的虚拟环境
  2. 启用类型检查:File → Settings → Editor → Inspections → Python
    • 启用 “Type checker” 相关检查
  3. 配置文档字符串风格:File → Settings → Tools → Python Integrated Tools
    • Docstring format: Google 或 NumPy

2.9.3 Jupyter Notebook 配置

# 安装 Jupyter
pip install jupyterlab

# 安装 Shapely 可视化支持
pip install matplotlib descartes

# 启动 Jupyter
jupyter lab
# Notebook 中的 Shapely 使用体验
from shapely import Point, Polygon
import matplotlib.pyplot as plt

# Shapely 几何体在 Jupyter 中有内置的 SVG 显示
polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
polygon  # 直接显示 SVG 图形

2.10 依赖库推荐

2.10.1 核心推荐

# 最小安装——仅 Shapely
pip install shapely

# 标准 GIS 安装
pip install shapely numpy geopandas matplotlib

# 完整 GIS 工具链
pip install shapely numpy geopandas fiona pyproj matplotlib folium

2.10.2 推荐搭配库

库名 用途 安装命令
numpy 数值计算,Shapely 2.0 的核心依赖 pip install numpy
matplotlib 几何体可视化 pip install matplotlib
geopandas 空间数据框分析 pip install geopandas
fiona 空间数据文件 I/O pip install fiona
pyproj 坐标参考系转换 pip install pyproj
folium Web 地图可视化 pip install folium
scipy 科学计算(空间分析扩展) pip install scipy
rtree 空间索引(R-tree) pip install rtree

2.10.3 版本兼容性矩阵

# 检查已安装的 GIS 库版本
import importlib

libs = ['shapely', 'numpy', 'geopandas', 'fiona', 'pyproj']
for lib_name in libs:
    try:
        lib = importlib.import_module(lib_name)
        version = getattr(lib, '__version__', '未知')
        print(f"{lib_name:15s} {version}")
    except ImportError:
        print(f"{lib_name:15s} 未安装")

# 示例输出:
# shapely         2.0.6
# numpy           1.26.4
# geopandas       0.14.3
# fiona           1.9.6
# pyproj          3.6.1

2.11 安装验证完整脚本

将以下脚本保存为 verify_shapely.py,运行以完整验证安装:

"""Shapely 安装验证脚本"""

def verify_installation():
    print("=" * 50)
    print("Shapely 安装验证")
    print("=" * 50)

    # 1. 基本导入
    try:
        import shapely
        print(f"✅ Shapely 版本: {shapely.__version__}")
    except ImportError as e:
        print(f"❌ Shapely 导入失败: {e}")
        return

    # 2. GEOS 版本
    print(f"✅ GEOS 版本: {'.'.join(map(str, shapely.geos_version))}")
    print(f"✅ GEOS C API 版本: {'.'.join(map(str, shapely.geos_capi_version))}")

    # 3. 几何体创建
    from shapely import Point, LineString, Polygon
    p = Point(1, 2)
    line = LineString([(0, 0), (1, 1)])
    poly = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
    print(f"✅ 几何体创建: Point={p}, Line长度={line.length:.4f}, Polygon面积={poly.area}")

    # 4. 空间运算
    buffer = p.buffer(1)
    intersection = poly.intersection(buffer)
    print(f"✅ 空间运算: 缓冲区面积={buffer.area:.4f}, 交集面积={intersection.area:.4f}")

    # 5. 向量化操作
    import numpy as np
    coords = np.array([[0, 0], [1, 1], [2, 2]])
    points = shapely.points(coords)
    distances = shapely.distance(points, Point(0, 0))
    print(f"✅ 向量化操作: 距离={distances}")

    # 6. WKT / WKB
    wkt = poly.wkt
    wkb = poly.wkb_hex
    print(f"✅ 序列化: WKT 长度={len(wkt)}, WKB 长度={len(wkb)}")

    # 7. 有效性检查
    print(f"✅ 有效性: {poly.is_valid}")

    print("=" * 50)
    print("所有验证通过!Shapely 安装正确。")
    print("=" * 50)

if __name__ == "__main__":
    verify_installation()

运行验证:

python verify_shapely.py

2.12 本章小结

本章我们学习了:

  • 系统要求:Python 3.8+,支持 Windows/macOS/Linux
  • pip 安装:最简单的方式,预编译 wheel 已包含 GEOS
  • conda 安装:适合与其他 GIS 库配合使用
  • 源码编译:需要 GEOS 开发库和 Cython
  • GEOS 管理:版本检查和路径配置
  • 虚拟环境:venv、conda env、Poetry 三种方式
  • Docker 部署:容器化 GIS 环境
  • 常见问题:GEOS 找不到、版本冲突、wheel 不匹配等的解决方案
  • IDE 配置:VSCode 和 PyCharm 的最佳配置
  • 依赖推荐:numpy、matplotlib、geopandas 等搭配库

下一章我们将深入学习 Shapely 的几何对象模型。