

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在 EMR Serverless 中使用不同的 Python 版本
<a name="using-python"></a>

除了 [将 Python 库与 EMR Serverless 结合使用](using-python-libraries.md) 中的用例之外，您还可以使用 Python 虚拟环境来处理不同于 Amazon EMR 发行版中打包的 Amazon EMR Serverless 应用程序版本的 Python 版本。为此，请使用想要的 Python 版本构建 Python 虚拟环境。

**从 Python 虚拟环境提交作业**

1. 使用以下示例中的命令构建虚拟环境。此示例将 Python 3.9.9 安装到虚拟环境包中，并将存档复制到 Amazon S3 位置。
**重要**  
如果使用 Amazon EMR 7.0.0 及更高版本，请在类似于 EMR Serverless 应用程序所用环境的 Amazon Linux 2023 环境中运行命令。  
 如果使用 6.15.0 或更低版本，请在类似 Amazon Linux 2 环境中运行以下命令。

   ```
   # install Python 3.9.9 and activate the venv
   yum install -y gcc openssl-devel bzip2-devel libffi-devel tar gzip wget make
   wget https://www.python.org/ftp/python/3.9.9/Python-3.9.9.tgz && \
   tar xzf Python-3.9.9.tgz && cd Python-3.9.9 && \
   ./configure --enable-optimizations --enable-shared && \
   make altinstall
   
   # create python venv with Python 3.9.9
   python3.9 -m venv pyspark_venv_python_3.9.9 --copies 
   source pyspark_venv_python_3.9.9/bin/activate
   
   # copy system python3 libraries and shared libraries to venv
   cp -r /usr/local/lib/python3.9/* ./pyspark_venv_python_3.9.9/lib/python3.9/
   cp /usr/local/lib/libpython3.9* ./pyspark_venv_python_3.9.9/lib/
   
   # package venv to archive. 
   # **Note** that you have to supply --python-prefix option 
   # to make sure python starts with the path where your 
   # copied libraries are present.
   # Copying the python binary to the "environment" directory.
   pip3 install venv-pack
   venv-pack -f -o pyspark_venv_python_3.9.9.tar.gz --python-prefix /home/hadoop/environment
   
   # stage the archive in S3 
   aws s3 cp pyspark_venv_python_3.9.9.tar.gz s3://<path>
   
   # optionally, remove the virtual environment directory
   rm -fr pyspark_venv_python_3.9.9
   ```

1. 设置属性以使用 Python 虚拟环境，然后提交 Spark 作业。

   ```
   # note that the archive suffix "environment" is the same as the directory where you copied the Python binary.
   --conf spark.archives=s3://amzn-s3-demo-bucket/EXAMPLE-PREFIX/pyspark_venv_python_3.9.9.tar.gz#environment 
   --conf spark.emr-serverless.driverEnv.PYSPARK_DRIVER_PYTHON=./environment/bin/python
   --conf spark.emr-serverless.driverEnv.PYSPARK_PYTHON=./environment/bin/python 
   --conf spark.executorEnv.PYSPARK_PYTHON=./environment/bin/python
   --conf spark.emr-serverless.driverEnv.LD_LIBRARY_PATH=./environment/lib
   --conf spark.executorEnv.LD_LIBRARY_PATH=./environment/lib
   ```

有关如何使用 Python 虚拟环境进行 PySpark 作业的更多信息，请参阅[使用 Virtualenv](https://spark.apache.org/docs/latest/api/python/tutorial/python_packaging.html#using-virtualenv)。有关如何提交 Spark 作业的更多示例，请参阅[运行 EMR Serverless 作业时使用 Spark 配置](jobs-spark.md)。