

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

除了 中的使用案例之外[搭配 EMR Serverless 使用 Python 程式庫](using-python-libraries.md)，您也可以使用 Python 虛擬環境來使用與 Amazon EMR Serverless 應用程式 Amazon EMR 版本中封裝的版本不同的 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
   ```

如需如何為 PySpark 任務使用 Python 虛擬環境的詳細資訊，請參閱[使用 Virtualenv](https://spark.apache.org/docs/latest/api/python/tutorial/python_packaging.html#using-virtualenv)。如需如何提交 Spark 任務的更多範例，請參閱 [執行 EMR Serverless 任務時使用 Spark 組態](jobs-spark.md)。