

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

# 在 AWS Glue 中設定 Python Shell 任務的任務屬性
<a name="add-job-python"></a>

 您可以使用 Python shell 任務，在 AWS Glue 中以 shell 的方式執行 Python 指令碼。您可以透過 Python Shell 任務，來執行與 Python 3.6 或 Python 3.9 相容的指令碼。

**注意**  
 Pyshell v3.6 的支援將在 2026 年 3 月 1 日結束。若要遷移工作負載，請參閱[從 AWS Glue Python shell 任務遷移](https://docs.aws.amazon.com/glue/latest/dg/pyshell-migration.html)。如果您想要繼續使用 Python Shell v3.9，請參閱[從 Python Shell 3.6 移轉至 Python Shell 3.9](#migrating-version-pyshell36-to-pyshell39)。

**Topics**
+ [限制](#python-shell-limitations)
+ [執行環境](#python-shell-execution-environment)
+ [為 Python shell 任務定義任務屬性](#create-job-python-properties)
+ [適用於 Python shell 任務的支援程式庫](#python-shell-supported-library)
+ [提供自己的 Python 程式庫](#create-python-extra-library)
+ [在 中使用 AWS CloudFormation 搭配 Python shell 任務 AWS Glue](#python-shell-jobs-cloudformation)
+ [從 Python Shell 3.6 移轉至 Python Shell 3.9](#migrating-version-pyshell36-to-pyshell39)
+ [從 AWS Glue Python shell 任務遷移](pyshell-migration.md)

## 限制
<a name="python-shell-limitations"></a>

注意 Python Shell 任務的下列限制：
+  您無法使用任務書籤搭配 Python shell 任務。
+ 您不能將任何 Python 程式庫打包為 Python 3.9 \$1 中的 `.egg` 檔案。請改用 `.whl`。
+ 由於 S3 資料的暫時複本有限制，`--extra-files` 選項無法使用。

## 執行環境
<a name="python-shell-execution-environment"></a>

Python shell 任務會在受管執行環境中執行，提供存取本機儲存以進行臨時資料處理：

**本機暫時儲存**  
`/tmp` 目錄可在任務執行期間用於暫時儲存。此目錄提供大約 14 GiB 的可用空間，可用於：  
+ 臨時檔案處理
+ 中繼資料儲存
+ 快取小型資料集
`/tmp` 目錄是暫時性的，會在任務完成後清除。請勿將其用於持續儲存重要資料。

## 為 Python shell 任務定義任務屬性
<a name="create-job-python-properties"></a>

這些章節說明在 中AWS Glue Studio或使用 AWS CLI 定義任務屬性。

### AWS Glue Studio
<a name="create-job-python-properties-studio"></a>

當您在 AWS Glue Studio 中定義 Python Shell 任務時，您會提供以下一些屬性：

**IAM 角色**  
指定 AWS Identity and Access Management (IAM) 角色，用於授權用於執行任務和存取資料存放區的資源。如需在 AWS Glue 執行任務之許可的詳細資訊，請參閱 [Glue AWS 的身分和存取管理](security-iam.md)。

**Type**  
選擇 **Python shell (Python shell)** 來​使用名為 `pythonshell` 的任務執行 Python 指令碼。

**Python 版本**  
選擇 Python 版本。預設為 Python 3.9。有效版本為 Python 3.6 和 Python 3.9。

**載入常見的分析程式庫 (建議)**  
選擇此選項可在 Python Shell 中包含 Python 3.9 的常見程式庫。  
如果您的程式庫是自訂的，或者與預先安裝的程式庫衝突，您可以選擇不安裝常見程式庫。但是，除了常見程式庫之外，您還可以安裝其他程式庫。  
當您選取此選項時，`library-set` 選項設定為 `analytics`。當您取消選取此選項時，`library-set` 選項設定為 `none`。

**指令碼檔案名稱和指令碼路徑**  
指令碼中的程式碼定義了任務的程序性邏輯。您可以在 Amazon Simple Storage Service (Amazon S3) 中提供指令碼名稱和位置。請確認路徑中沒有跟指令碼目錄名稱相同的檔案。若要進一步了解使用指令碼，請參閱 [AWS Glue 程式設計指南](edit-script.md)。

**指令碼**  
指令碼中的程式碼定義了任務的程序性邏輯。您可以使用 Python 3.6 或 Python 3.9 編寫指令碼。您可以在 AWS Glue Studio 中編輯指令碼。

**資料處理單位**  
可在此任務執行時分配的 AWS Glue 資料處理單位​ (DPU) 數目上限。DPU 是處理能力的相對測量，由 4 個 vCPUs的運算容量和 16 GB 的記憶體組成。如需詳細資訊，請參閱 [AWS Glue 定價](https://aws.amazon.com/glue/pricing/)。  
您可以將值設為 0.0625 或 1。預設為 0.0625。在任一情況下，執行個體的本機磁碟都是 20 GB。

### CLI
<a name="create-job-python-properties-cli"></a>

 您也可以使用 建立 **Python shell** 任務 AWS CLI，如下列範例所示。

```
 aws glue create-job --name python-job-cli --role Glue_DefaultRole 
     --command '{"Name" :  "pythonshell", "PythonVersion": "3.9", "ScriptLocation" : "s3://amzn-s3-demo-bucket/scriptname.py"}'  
     --max-capacity 0.0625
```

**注意**  
 您不需要指定 AWS Glue 的版本，因為參數 `--glue-version` 不適用於 AWS Glue Shell 任務。任何指定的版本都會予以忽略。

 您使用 AWS CLI 預設為 Python 3 建立的任務。有效的 Python 版本為 3 (對應於 3.6) 和 3.9。若要指定 Python 3.6，請將此元組新增至 `--command` 參數：`"PythonVersion":"3"`

 若要指定 Python 3.9，請將此元組新增至 `--command` 參數：`"PythonVersion":"3.9"`

 若要設定 Python shell 任務所用的容量上限，請提供 `--max-capacity` 參數。​ 無法將 `--allocated-capacity` 參數用於 Python shell 任務。

## 適用於 Python shell 任務的支援程式庫
<a name="python-shell-supported-library"></a>

 在使用 Python 3.9 的 Python Shell 中，您可以選擇程式庫集來使用預先封裝的程式庫集來滿足您的需求。您可以使用 `library-set` 選項來選擇程式庫集。有效值為 `analytics` 和 `none`。

執行 Python shell 任務的環境支援以下程式庫：


| Python 版本 | Python 3.6 | Python 3.9 | 
| --- | --- | --- | 
| 程式庫集 | 無 | 分析 | 無 | 
| avro |  | 1.11.0 |  | 
| awscli | 116.242 | 1.23.5 | 1.23.5 | 
| awswrangler |  | 2.15.1 |  | 
| botocore | 1.12.232 | 1.24.21 | 1.23.5 | 
| boto3 | 203 年 9 月 1 日 | 1.21.21 |  | 
| elasticsearch |  | 8.2.0 |  | 
| numpy | 1.16.2 | 1.22.3 |  | 
| pandas | 0.24.2 | 1.4.2 |  | 
| psycopg2 |  | 2.9.3 |  | 
| pyathena |  | 2.5.3 |  | 
| PyGreSQL | 5.0.6 |  |  | 
| PyMySQL |  | 1.0.2 |  | 
| pyodbc |  | 4.0.32 |  | 
| pyorc |  | 0.6.0 |  | 
| redshift-connector |  | 2.0.907 |  | 
| 請求 | 2.22.0 | 2.27.1 |  | 
| scikit-learn | 0.20.3 | 1.0.2 |  | 
| scipy | 1.2.1 | 1.8.0 |  | 
| SQLAlchemy |  | 1.4.36 |  | 
| s3fs |  | 2022.3.0 |  | 

您可以在 Python shell 任務中使用 `NumPy`​ 程式庫以進行科學運算。如需詳細資訊，請參閱 [NumPy](http://www.numpy.org) 相關文章。以下範例顯示的 NumPy 指令碼可用於 Python shell 任務。指令碼會列印「Hello world」和多個數學計算的結果。

```
import numpy as np
print("Hello world")

a = np.array([20,30,40,50])
print(a)

b = np.arange( 4 )

print(b)

c = a-b

print(c)

d = b**2

print(d)
```

## 提供自己的 Python 程式庫
<a name="create-python-extra-library"></a>

### 使用 PIP
<a name="create-python-extra-library-pip"></a>

Python Shell 使用 Python 3.9 允許您在任務層級提供額外的 Python 模組或不同的版本。您可以使用 `--additional-python-modules` 選項與逗號分隔的 Python 模組清單來新增新模組或變更現有模組的版本。使用 Python Shell 任務時，您無法使用此參數來提供在 Amazon S3 上託管的自訂 Python 模組。

例如，要更新或新增新的 `scikit-learn` 模組，請使用以下索引鍵與值：`"--additional-python-modules", "scikit-learn==0.21.3"`。

AWS Glue 使用 Python Package Installer (pip3) 來安裝其他模組。您可以在 `--additional-python-modules` 值內傳遞額外的 pip3 選項。例如 `"scikit-learn==0.21.3 -i https://pypi.python.org/simple/"`。來自 pip3 的任何不相容或限制都適用。

**注意**  
為避免未來出現不相容，我們建議您使用為 Python 3.9 建置的程式庫。

### 使用 Egg 或 Whl 文件
<a name="create-python-extra-library-egg-whl"></a>

您可能已有一或多個 Python 程式庫封裝為 `.egg` 或 `.whl` 檔案。若是如此，您可以使用「`--extra-py-files`」旗標下的 AWS Command Line Interface (AWS CLI)，將它們指定到您的任務，如下列範例所示。

```
aws glue create-job --name python-redshift-test-cli --role role --command '{"Name" :  "pythonshell", "ScriptLocation" : "s3://MyBucket/python/library/redshift_test.py"}' 
     --connections Connections=connection-name --default-arguments '{"--extra-py-files" : ["s3://amzn-s3-demo-bucket/EGG-FILE", "s3://amzn-s3-demo-bucket/WHEEL-FILE"]}'
```

如果您不確定如何從 Python 程式庫建立 `.egg` 或 `.whl` 檔案，請使用以下步驟。此範例適用於 macOS、Linux 和適用於 Linux 的 Windows 子系統 (WSL)。

**建立 Python .egg 或 .whl 檔案**

1. 在 Virtual Private Cloud (VPC) 建立 Amazon Redshift 叢集並將一些資料新增到資料表。

1. 為您在建立叢集時所用的 VPC-SecurityGroup-Subnet 組合建立 AWS Glue 連線。​ 測試連線是否成功。

1. 建立名為 `redshift_example` 的目錄，並建立名為 `setup.py` 的檔案。​ 將以下程式碼貼入 `setup.py`。

   ```
   from setuptools import setup
   
   setup(
       name="redshift_module",
       version="0.1",
       packages=['redshift_module']
   )
   ```

1. 在 `redshift_example` 目錄中，建立 `redshift_module` 目錄。​在 `redshift_module`​ 目錄中，建立檔案 `__init__.py` 和 `pygresql_redshift_common.py`。

1. 將 `__init__.py` 檔案留空。在 `pygresql_redshift_common.py` 中貼上以下程式碼。在先前的程式碼中，將 *port*、*db\$1name*、*user*​ 和 *password\$1for\$1user* 取代為 Amazon Redshift 叢集的特定詳細資訊。將 *table-name* 取代為 Amazon Redshift 中的資料表名稱。

   ```
   import pg
   
   
   def get_connection(host):
       rs_conn_string = "host=%s port=%s dbname=%s user=%s password=%s" % (
           host, port, db_name, user, password_for_user)
   
       rs_conn = pg.connect(dbname=rs_conn_string)
       rs_conn.query("set statement_timeout = 1200000")
       return rs_conn
   
   
   def query(con):
       statement = "Select * from table_name;"
       res = con.query(statement)
       return res
   ```

1. 如果您尚未這麼做，請變更至 `redshift_example` 目錄。​

1. 執行以下任意一項：
   + 執行下列命令以建立 `.egg` 檔案。

     ```
     python setup.py bdist_egg
     ```
   + 執行下列命令以建立 `.whl` 檔案。

     ```
     python setup.py bdist_wheel
     ```

1. 安裝上述命令所需的相依項目。

1. 該命令會在 `dist` 目錄中建立檔案。
   + 如果您建立了 egg 檔案，會命名為 `redshift_module-0.1-py2.7.egg`。
   + 如果您建立了 wheel 檔案，會命名為 `redshift_module-0.1-py2.7-none-any.whl`。

   將此檔案上傳到 Amazon S3。

   在此範例中，上傳的檔案路徑為 *s3://amzn-s3-demo-bucket/EGG-FILE* 或 *s3://amzn-s3-demo-bucket/WHEEL-FILE*。

1. 建立要用來做為 AWS Glue 任務之指令碼的​ Python 檔案，並將以下程式碼新增到該檔案。

   ```
   from redshift_module import pygresql_redshift_common as rs_common
   
   con1 = rs_common.get_connection(redshift_endpoint)
   res = rs_common.query(con1)
   
   print "Rows in the table cities are: "
   
   print res
   ```

1. 將上述檔案上傳到 Amazon S3。在此範例中，上傳的檔案路徑為 *s3://amzn-s3-demo-bucket/scriptname.py*。

1. 使用此指令碼建立 Python shell 任務。在 AWS Glue 主控台的 **Job properties (任務屬性)** 頁面上，在 **Python library path (Python 程式庫路徑)** 方塊中指定 `.egg/.whl` 檔案的路徑。如果您有多個 `.egg/.whl` 檔案和​ Python 檔案，請在此方塊中提供以逗號分隔的清單。

   修改或重新命名 `.egg` 檔案時，檔案名稱必須使用由「python setup.py bdist\$1egg」指令產生的預設名稱，或必須承繼 Python 模組命名慣例。如需詳細資訊，請參閱 [Python 程式碼樣式指南](https://www.python.org/dev/peps/pep-0008/)。

   使用 AWS CLI，透過 命令建立任務，如下列範例所示。

   ```
   aws glue create-job --name python-redshift-test-cli --role Role --command '{"Name" :  "pythonshell", "ScriptLocation" : "s3://amzn-s3-demo-bucket/scriptname.py"}' 
        --connections Connections="connection-name" --default-arguments '{"--extra-py-files" : ["s3://amzn-s3-demo-bucket/EGG-FILE", "s3://amzn-s3-demo-bucket/WHEEL-FILE"]}'
   ```

   當任務執行時，指令碼會列印在 Amazon Redshift 叢集 *table\$1name* 資料表中建立的列。

## 在 中使用 AWS CloudFormation 搭配 Python shell 任務 AWS Glue
<a name="python-shell-jobs-cloudformation"></a>

 您可以在 中使用 AWS CloudFormation 搭配 Python shell 任務AWS Glue。以下是範例：

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  Python39Job:
    Type: 'AWS::Glue::Job'
    Properties:
      Command:
        Name: pythonshell
        PythonVersion: '3.9'
        ScriptLocation: 's3://bucket/location'
      MaxRetries: 0
      Name: python-39-job
      Role: RoleName
```

 Python shell 任務輸出的 Amazon CloudWatch Logs 群組是 `/aws-glue/python-jobs/output`。針對錯誤，請參閱日誌群組 `/aws-glue/python-jobs/error`。​ 

## 從 Python Shell 3.6 移轉至 Python Shell 3.9
<a name="migrating-version-pyshell36-to-pyshell39"></a>

 若要將 Python shell 任務遷移至 AWS Glue 最新版本：

1.  在 AWS Glue 主控台 ([https://console.aws.amazon.com/glue/](https://console.aws.amazon.com/glue/)：//) 中，選擇現有的 Python shell 任務。

1.  在**任務**詳細資訊索引標籤中，將 Python 版本設定為 `Python 3.9`，然後選擇**儲存**。

1.  確保您的任務指令碼與 Python 3.9 相容，且成功執行。