

 AWS Cloud9 不再提供給新客戶。 AWS Cloud9 的現有客戶可以繼續正常使用該服務。[進一步了解](https://aws.amazon.com/blogs/devops/how-to-migrate-from-aws-cloud9-to-aws-ide-toolkits-or-aws-cloudshell/)

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

# 的 Python 教學課程 AWS Cloud9
<a name="sample-python"></a>

本教學課程說明如何在 AWS Cloud9 開發環境中執行 Python 程式碼。

遵循本教學課程可能會導致 AWS 您的帳戶產生費用。包括 Amazon Elastic Compute Cloud (Amazon EC2) 和 Amazon Simple Storage Service (Amazon S3) 等服務的可能費用。如需詳細資訊，請參閱 [Amazon EC2 定價](https://aws.amazon.com/ec2/pricing/)和 [Amazon S3 定價](https://aws.amazon.com/s3/pricing/)。

**Topics**
+ [先決條件](#sample-python-prereqs)
+ [步驟 1：安裝 Python](#sample-python-install)
+ [步驟 2：新增程式碼](#sample-python-code)
+ [步驟 3：執行程式碼](#sample-python-run)
+ [步驟 4：安裝和設定 適用於 Python (Boto3) 的 AWS SDK](#sample-python-sdk)
+ [步驟 5：新增 AWS SDK 程式碼](#sample-python-sdk-code)
+ [步驟 6：執行 AWS SDK 程式碼](#sample-python-sdk-run)
+ [步驟 7：清除](#sample-python-clean-up)

## 先決條件
<a name="sample-python-prereqs"></a>

在您使用此教學前，請務必符合下列要求。
+ **您有 an AWS Cloud9 EC2 開發環境**

  此教學假設您已具備 EC2 環境，且該環境已連線到執行 Amazon Linux 或 Ubuntu Server 的 Amazon EC2 執行個體。如需詳細資訊，請參閱 [建立 EC2 環境](create-environment-main.md)。

  如果您有不同類型的環境或作業系統，您可能需要調整此教學的操作指示。
+ **您已開啟該環境的 AWS Cloud9 IDE**

  當您開啟環境時，請在 Web 瀏覽器中 AWS Cloud9 開啟該環境的 IDE。如需詳細資訊，請參閱 [在 中開啟環境 AWS Cloud9](open-environment.md)。

## 步驟 1：安裝 Python
<a name="sample-python-install"></a>

1. 在 IDE AWS Cloud9 的終端機工作階段中，執行 **`python --version`**命令以確認是否已安裝 Python。(若要啟動新終端機工作階段，請在選單列上，選擇 **Window (視窗)**、**New Terminal (新增終端機)**。) 若 Python 已安裝，請跳至[步驟 2：新增程式碼](#sample-python-code)。

1. 執行 **`yum update`** (適用於 Amazon Linux) 或 **`apt update`** (適用於 Ubuntu Server) 命令，協助確保已安裝最新安全性更新和錯誤修正。

   針對 Amazon Linux：

   ```
   sudo yum -y update
   ```

   針對 Ubuntu Server：

   ```
   sudo apt update
   ```

1. 執行 **`install`** 命令以安裝 Python。

   針對 Amazon Linux：

   ```
   sudo yum -y install python3
   ```

   針對 Ubuntu Server：

   ```
   sudo apt-get install python3
   ```

## 步驟 2：新增程式碼
<a name="sample-python-code"></a>

在 AWS Cloud9 IDE 中，使用下列內容建立檔案，並使用名稱 儲存檔案`hello.py`。(若要建立檔案，請在選單列上選擇 **File** (檔案)、**New File** (新增檔案)。若要儲存檔案，請選擇 **File** (檔案)、**Save** (儲存)。)

```
import sys

print('Hello, World!')

print('The sum of 2 and 3 is 5.')

sum = int(sys.argv[1]) + int(sys.argv[2])

print('The sum of {0} and {1} is {2}.'.format(sys.argv[1], sys.argv[2], sum))
```

## 步驟 3：執行程式碼
<a name="sample-python-run"></a>

1. 在 AWS Cloud9 IDE 的選單列中，選擇**執行**、**執行組態**、**新執行組態**。

1. 在 **[New] - Stopped** ([新增] - 已停止) 索引標籤中，為 **Command** (命令) 輸入 `hello.py 5 9`。此程式碼的 `5` 代表 `sys.argv[1]`，而 `9` 代表 `sys.argv[2]`。

1. 選擇 **Run (執行)**，然後比較您的輸出。

   ```
   Hello, World!
   The sum of 2 and 3 is 5.
   The sum of 5 and 9 is 14.
   ```

1. 根據預設， AWS Cloud9 會自動為您的程式碼選取執行器。若要變更執行器，請選擇 **Runner (執行器)**，然後選擇 **Python 2** 或 **Python 3**。
**注意**  
您可以為特定版本的 Python 建立自訂的執行器。如需詳細資訊，請參閱[建立建置器或執行器](build-run-debug.md#build-run-debug-create-builder-runner)。

## 步驟 4：安裝和設定 適用於 Python (Boto3) 的 AWS SDK
<a name="sample-python-sdk"></a>

 適用於 Python (Boto3) 的 AWS SDK 可讓您使用 Python 程式碼與 Amazon S3 等 AWS 服務互動。例如，您可以使用 SDK 來建立 Amazon S3 儲存貯體、列出可用的儲存貯體，然後刪除您剛建立的儲存貯體。

### 安裝 pip
<a name="sample-python-sdk-install-pip"></a>

在 AWS Cloud9 IDE 中，執行 **`python -m pip --version`**命令，確認`pip`是否已為作用中版本的 Python 安裝 。如果已安裝 `pip`，請跳到下一節。

若要安裝 `pip`，請執行以下命令。由於 sudo 與使用者的環境不同，如果它與目前別名版本不同，則必須指定要使用的 Python 版本。

```
curl -O https://bootstrap.pypa.io/get-pip.py # Get the install script.
sudo python3 get-pip.py                     # Install pip for Python 3.
python -m pip --version                      # Verify pip is installed.
rm get-pip.py                                # Delete the install script.
```

如需詳細資訊，請參閱 `pip` 網站文章[安裝](https://pip.pypa.io/en/stable/installing/)。

### 安裝 適用於 Python (Boto3) 的 AWS SDK
<a name="sample-python-sdk-install-sdk"></a>

安裝 之後`pip`， 適用於 Python (Boto3) 的 AWS SDK 請執行 **`pip install`**命令來安裝 。

```
sudo python3 -m pip install boto3  # Install boto3 for Python 3.
python -m pip show boto3            # Verify boto3 is installed for the current version of Python.
```

如需詳細資訊，請參閱《[》](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)快速入門 適用於 Python (Boto3) 的 AWS SDK的「安裝」一節。

### 在環境中設定憑證
<a name="sample-python-sdk-credentials"></a>

每次使用 適用於 Python (Boto3) 的 AWS SDK 來呼叫 AWS 服務時，您必須隨呼叫提供一組登入資料。這些登入資料會判斷 SDK 是否具備適當許可，能夠發出該次呼叫。如果登入資料未涵蓋必要的許可，呼叫會失敗。

若要將憑證存放在環境中，請遵循 [AWS 服務 從 中的環境呼叫 AWS Cloud9](credentials.md) 中的指示，然後返回本主題。

如需詳細資訊，請參閱《[》章節](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html)登入資料 適用於 Python (Boto3) 的 AWS SDK。

## 步驟 5：新增 AWS SDK 程式碼
<a name="sample-python-sdk-code"></a>

新增使用 Amazon S3 來建立儲存貯體的程式碼、列出可用的儲存貯體，並選擇性刪除您剛建立的儲存貯體。

在 AWS Cloud9 IDE 中，使用下列內容建立檔案，並使用名稱 儲存檔案`s3.py`。

```
import sys
import boto3
from botocore.exceptions import ClientError


def list_my_buckets(s3_resource):
    print("Buckets:\n\t", *[b.name for b in s3_resource.buckets.all()], sep="\n\t")


def create_and_delete_my_bucket(s3_resource, bucket_name, keep_bucket):
    list_my_buckets(s3_resource)

    try:
        print("\nCreating new bucket:", bucket_name)
        bucket = s3_resource.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={
                "LocationConstraint": s3_resource.meta.client.meta.region_name
            },
        )
    except ClientError as e:
        print(
            f"Couldn't create a bucket for the demo. Here's why: "
            f"{e.response['Error']['Message']}"
        )
        raise

    bucket.wait_until_exists()
    list_my_buckets(s3_resource)

    if not keep_bucket:
        print("\nDeleting bucket:", bucket.name)
        bucket.delete()

        bucket.wait_until_not_exists()
        list_my_buckets(s3_resource)
    else:
        print("\nKeeping bucket:", bucket.name)


def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("bucket_name", help="The name of the bucket to create.")
    parser.add_argument("region", help="The region in which to create your bucket.")
    parser.add_argument(
        "--keep_bucket",
        help="Keeps the created bucket. When not "
        "specified, the bucket is deleted "
        "at the end of the demo.",
        action="store_true",
    )

    args = parser.parse_args()
    s3_resource = (
        boto3.resource("s3", region_name=args.region)
        if args.region
        else boto3.resource("s3")
    )
    try:
        create_and_delete_my_bucket(s3_resource, args.bucket_name, args.keep_bucket)
    except ClientError:
        print("Exiting the demo.")


if __name__ == "__main__":
    main()
```

## 步驟 6：執行 AWS SDK 程式碼
<a name="sample-python-sdk-run"></a>

1. 在選單列上，選擇 **Run** (執行)、**Run Configurations** (執行組態)、**New Run Configuration** (新增執行組態)。

1. 在**命令**中，輸入 `s3.py my-test-bucket us-west-2`，其中 `my-test-bucket`是要建立的儲存貯體名稱，而 `us-west-2`是建立儲存貯 AWS 體的區域 ID。預設情況下，指令碼結束之前，會先刪除您的儲存貯體。若要要保留您的儲存貯體，請將 `--keep_bucket` 新增到您的命令中。如需 AWS 區域 IDs 的清單，請參閱《》中的 [Amazon Simple Storage Service 端點和配額](https://docs.aws.amazon.com/general/latest/gr/s3.html)*AWS 一般參考*。
**注意**  
Amazon S3 儲存貯體名稱必須是唯一的 AWS，而不只是您的帳戶 AWS 。

1. 選擇 **Run (執行)**，然後比較您的輸出。

   ```
   Buckets:
   
           a-pre-existing-bucket
   
   Creating new bucket: my-test-bucket
   Buckets:
   
           a-pre-existing-bucket
           my-test-bucket
   
   Deleting bucket: my-test-bucket
   Buckets:
   
           a-pre-existing-bucket
   ```

## 步驟 7：清除
<a name="sample-python-clean-up"></a>

若要避免在您完成本教學課程後持續向您的 AWS 帳戶收取費用，請刪除 AWS Cloud9 環境。如需說明，請參閱[在 中刪除環境 AWS Cloud9](delete-environment.md)。