PySpark 的 Python 依赖管理:把环境一同送到执行器

原作者:Apache Spark 文档贡献者。本文完整译写自官方 Python Package Management,核对日期为 2026-10-05;读取时页面标示为 PySpark 4.2.0 文档。latest 是会变化的地址,实际部署应以集群安装版本为准。

在 YARN、Kubernetes 等集群上运行 PySpark 应用,不能只保证驱动程序所在机器装了依赖:执行器同样需要应用代码和使用的库。本文保留原文的原生文件分发、Conda、Virtualenv、PEX 和 uv 全部章节,其中前三种环境封装路线给出了完整的提交示例。命令均为文档示例,本次没有建立集群或执行作业。

Conda 和 venv-pack 生成归档,通过 archives 解压到 environment;PEX 通过 files 分发为单文件。三种方法分别把 PYSPARK_PYTHON 指向环境解释器或 PEX,venv 与 PEX 仍需要节点上的兼容 Python。
依赖包、分发参数与执行器解释器的对应关系。原创示意图,非运行截图。

为什么驱动端装好依赖还不够

以 Pandas UDF 为例,它的底层实现使用 pyarrow。如果执行器没有安装这个库,就可能出现 ModuleNotFoundError: No module named 'pyarrow'。原文使用下面的 app.py,按 id 分组,对数值列求均值:

import pandas as pd
from pyspark.sql.functions import pandas_udf
from pyspark.sql import SparkSession

def main(spark):
    df = spark.createDataFrame(
        [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
        ("id", "v"))

    @pandas_udf("double")
    def mean_udf(v: pd.Series) -> float:
        return v.mean()

    print(df.groupby("id").agg(mean_udf(df['v'])).collect())

if __name__ == "__main__":
    main(SparkSession.builder.getOrCreate())

后文所有提交命令都假定已经保存此文件,并且驱动端已有与集群匹配的 Spark/PySpark 运行环境。collect() 会把结果拉回驱动端,这个五行数据的示例很小;不能把相同写法直接推广到不受控的大结果集。

一、用 PySpark 原生功能分发 Python 文件

PySpark 可以把单个 .py 文件、ZIP 格式的 Python 包以及 .egg 文件上传给执行器,入口有三个:

这适合附加自定义 Python 代码:可以分发单个文件,也可以把一个包压缩后上传。addPyFile() 还允许在作业已经启动之后上传代码。

它并不是通用环境管理器。此路径不支持直接加入 Wheel 包,因此不能据此解决带原生代码的依赖。特别是 pyarrow 这类依赖,不能只把下载到的 wheel 随意放进 --py-files 就认为环境完整了。

二、使用 Conda 打包解释器和依赖

Conda 管理 Python 环境;conda-pack 可把现有环境做成可重定位归档。原例为驱动端和执行器建立环境,并把 Python 解释器及相关依赖一起封装:

conda create -y -n pyspark_conda_env -c conda-forge pyarrow pandas conda-pack
conda activate pyspark_conda_env
conda pack -f -o pyspark_conda_env.tar.gz

编者注:-y 自动确认安装,-f 强制写入归档。执行前应核对软件源与输出路径,避免覆盖需要保留的包。原例未固定 Python、pandas、Arrow 版本;实际应用应固定兼容版本,并在与执行器相容的操作系统、CPU 架构和系统库环境中构建。可重定位不等于跨所有平台可运行。

使用 --archives,或者设置 spark.archives(在 YARN 对应 spark.yarn.dist.archives),Spark 会在执行器上自动解压归档。提交应用的原例是:

export PYSPARK_DRIVER_PYTHON=python # YARN/Kubernetes cluster 模式不要设置
export PYSPARK_PYTHON=./environment/bin/python
spark-submit --archives pyspark_conda_env.tar.gz#environment app.py

#environment 是归档解压后的目录别名,必须与 PYSPARK_PYTHON 中的 ./environment/bin/python 对上。PYSPARK_DRIVER_PYTHON 指定驱动端解释器,PYSPARK_PYTHON 指定 PySpark 使用的 Python;两者不能不分部署模式地照抄。YARN 或 Kubernetes 的 cluster 模式应去掉第一行,并清除此前已经设置的驱动解释器变量。

在普通 Python shell 或 notebook 中,原文使用下面的写法。应在创建 Spark 上下文之前配置环境变量;已有会话不能被想当然地视为已经切换环境。

import os
from pyspark.sql import SparkSession
from app import main

os.environ['PYSPARK_PYTHON'] = "./environment/bin/python"
spark = SparkSession.builder.config(
    "spark.archives",  # 在 YARN 中使用 'spark.yarn.dist.archives'
    "pyspark_conda_env.tar.gz#environment").getOrCreate()
main(spark)

交互式 pyspark shell 的对应命令如下:

export PYSPARK_DRIVER_PYTHON=python
export PYSPARK_PYTHON=./environment/bin/python
pyspark --archives pyspark_conda_env.tar.gz#environment

三、使用 Virtualenv 与 venv-pack

Virtualenv 用于建立隔离 Python 环境。自 Python 3.3 起,其中一部分能力成为标准库的 venv 模块。PySpark 可以配合 venv-pack,像使用 conda-pack 一样归档和分发环境:

python -m venv pyspark_venv
source pyspark_venv/bin/activate
pip install pyarrow pandas venv-pack
venv-pack -o pyspark_venv.tar.gz

这里使用的是 POSIX shell 的激活路径和命令。归档内有依赖与解释器入口,但 venv-pack 把 Python 解释器保存为符号链接,所以集群各节点必须安装相同且路径兼容的 Python 解释器。它不是包含独立 Python 二进制的跨机器万能包。

提交时同样利用 --archives 或相应配置自动解包:

export PYSPARK_DRIVER_PYTHON=python # YARN/Kubernetes cluster 模式不要设置
export PYSPARK_PYTHON=./environment/bin/python
spark-submit --archives pyspark_venv.tar.gz#environment app.py

在 YARN、Kubernetes cluster 模式下,依然不能设置 PYSPARK_DRIVER_PYTHON。Python shell 或 notebook 写法为:

import os
from pyspark.sql import SparkSession
from app import main

os.environ['PYSPARK_PYTHON'] = "./environment/bin/python"
spark = SparkSession.builder.config(
    "spark.archives",  # 在 YARN 中使用 'spark.yarn.dist.archives'
    "pyspark_venv.tar.gz#environment").getOrCreate()
main(spark)

交互 shell 写法为:

export PYSPARK_DRIVER_PYTHON=python
export PYSPARK_PYTHON=./environment/bin/python
pyspark --archives pyspark_venv.tar.gz#environment

四、使用 PEX 生成可执行依赖包

PEX 可把指定 Python 依赖组织成 .pex 文件。它类似一个可直接调用的 Python 环境,但仍要使用宿主上的 Python 解释器。原文构建命令是:

pip install pyarrow pandas pex
pex pyspark pyarrow pandas -o pyspark_pex_env.pex

得到的文件可以像解释器一样接收 -c:

./pyspark_pex_env.pex -c "import pandas; print(pandas.__version__)"

原文该命令下展示的输出是 1.1.5。这是旧的示例输出,不是当前安装会得到的版本,也不是本文的实测结果。由于构建命令没有锁定版本,不能用这行输出证明依赖可复现。

.pex 本身不包含 Python 解释器,集群各节点仍需要相同、兼容的解释器。它是普通文件而非待解压目录,所以应通过 spark.files(YARN 为 spark.yarn.dist.files)或者 --files 传输:

export PYSPARK_DRIVER_PYTHON=python # YARN/Kubernetes cluster 模式不要设置
export PYSPARK_PYTHON=./pyspark_pex_env.pex
spark-submit --files pyspark_pex_env.pex app.py

普通 Python shell 或 notebook 使用:

import os
from pyspark.sql import SparkSession
from app import main

os.environ['PYSPARK_PYTHON'] = "./pyspark_pex_env.pex"
spark = SparkSession.builder.config(
    "spark.files",  # 在 YARN 中使用 'spark.yarn.dist.files'
    "pyspark_pex_env.pex").getOrCreate()
main(spark)

交互式 shell 的命令几乎相同:

export PYSPARK_DRIVER_PYTHON=python
export PYSPARK_PYTHON=./pyspark_pex_env.pex
pyspark --files pyspark_pex_env.pex

原文还链接了使用 SparkSession.builder 与 PEX 部署独立 PySpark 的端到端 Docker 示例,其使用建立在 PEX 之上的 cluster-pack,以自动处理创建及上传 PEX 的中间步骤。该外部工程不属于本文已执行或已验证的部署结果。

五、uv run:保留原文短例,并说明缺口

原文新增章节介绍 uv:它可以根据 Python 脚本内联声明的依赖建立环境,在首次运行时解析和安装依赖,从而减少手动环境管理。文档先建议创建名为 uv_run 的包装脚本,展示的命令语法为:

exec uv run [--python <version>] "$@"

编者注:方括号表示可选参数,<version> 表示要替换的值,不能把整行元语法直接作为 shell 脚本运行。如果不指定版本,去掉可选部分后是 exec uv run "$@";如果指定,则应写成实际选定的版本。原文接着要求赋予脚本执行权限:

chmod +x uv_run
export PYSPARK_PYTHON=./uv_run
pyspark app.py

原文所附脚本用 PEP 723 内联脚本元数据 声明依赖:

#!/usr/bin/env -S uv run --script
#
# /// script
# dependencies = [
#   "pandas==2.2.3",
# ]
# ///

import pandas as pd
from pyspark.sql import SparkSession
from pyspark.sql.functions import pandas_udf

spark = SparkSession.builder.master("local[*]").appName("UvRunExample").getOrCreate()

df = spark.createDataFrame(
    [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
    ("id", "v"),
)

@pandas_udf("double")
def mean_udf(v: pd.Series) -> float:
    return v.mean()

print(df.groupby("id").agg(mean_udf(df["v"])).collect())

spark.stop()

编者核查:这段元数据只声明 pandas,脚本还导入 PySpark,Pandas UDF 还需要 Arrow;原例没有交代它们如何进入同一运行环境,也没有完整说明集群节点上的 uv、包装脚本分发、网络依赖解析和 worker 启动方式。local[*] 明确选择本地模式,不是 YARN/Kubernetes 集群部署证明。原文的 pyspark app.py 也不能未经版本核对便当作通用脚本提交方式;本文主要路线使用的是前述 spark-submit。

因此这一节保留为源文提供的探索性短例,不能把它单独称作“复制即可运行”的完整方案。若采用 uv,应先补齐并锁定依赖、确认解释器与 Spark 的兼容条件,再在隔离环境验证 driver 和 worker 的实际启动链。本文没有为缺失条件编造成功结果。

选择路线时核对什么

路线 如何分发 解释器条件 适用边界
原生文件分发 --py-files / addPyFile 由节点现有环境提供 适合自定义 Python 代码,不解决原生 wheel 依赖
Conda --archives 归档携带环境解释器 仍需 OS、架构、系统库相容
venv-pack --archives 解释器链接依赖节点安装 节点解释器与链接目标必须匹配
PEX --files 不内置解释器 需要兼容 Python 与原生依赖平台
uv 短例 本页未给完整集群分发流程 需额外核实 uv 与 worker 启动环境 依赖声明不完整,本次不视为独立复现方案

不要把凭证、个人配置或无关文件一并封进环境归档。分发的 Python 包最终会在集群执行,应核实包来源、版本锁定与归档内容。这里没有发现示例内存在实际硬编码秘密或由外部输入直接构造 shell 命令的情况,但这不构成完整安全审计结论。

来源与许可

来源:Apache Spark 官方文档:Python Package Management。版权声明:Copyright © 2026 The Apache Software Foundation。原文按 Apache License, Version 2.0 发布;许可证全文保留在下方。本文为中文译写,补充了部署模式、供应链、版本和 uv 短例的编辑说明,未声称由 Apache 背书。

审核方式为静态阅读与来源比对;未安装软件、未打包环境、未连接集群、未执行作业。所有示例输出均已注明来自原文。

原始版权与许可

Apache Spark;Copyright 2014 and onwards The Apache Software Foundation. This product includes software developed at The Apache Software Foundation (http://www.apache.org/). 此处保留与本文引用内容相关的原始 NOTICE;官方 NOTICE 来源。其他组件的密码学与Metrics说明不属于本文转载内容。

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容