AWS Cloud9 的 Python 教學課程 - AWS Cloud9

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

AWS Cloud9 的 Python 教學課程

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

遵循此教學可能會向您的 AWS 帳戶收取費用。包括 Amazon Elastic Compute Cloud (Amazon EC2) 和 Amazon Simple Storage Service (Amazon S3) 等服務的可能費用。如需詳細資訊,請參閱 Amazon EC2 定價Amazon S3 定價

先決條件

在您使用此教學前,請務必符合下列要求。

  • 您已有 AWS Cloud9 EC2 開發環境

    此教學假設您已具備 EC2 環境,且該環境已連線到執行 Amazon Linux 或 Ubuntu Server 的 Amazon EC2 執行個體。如需詳細資訊,請參閱 建立 EC2 環境

    如果您有不同類型的環境或作業系統,您可能需要調整此教學的操作指示。

  • 您已開啟該環境的 AWS Cloud9 IDE

    當您開啟環境時,AWS Cloud9 會在 Web 瀏覽器中開啟該環境的 IDE。如需詳細資訊,請參閱 在 AWS Cloud9 中開啟環境

步驟 1:安裝 Python

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

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

    針對 Amazon Linux:

    sudo yum -y update

    針對 Ubuntu Server:

    sudo apt update
  3. 執行 install 命令以安裝 Python。

    針對 Amazon Linux:

    sudo yum -y install python3

    針對 Ubuntu Server:

    sudo apt-get install python3

步驟 2:新增程式碼

在 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:執行程式碼

  1. 在 AWS Cloud9 IDE 的選單列上,選擇 Run (執行)、Run Configurations (執行組態)、New Run Configuration (新增執行組態)。

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

  3. 選擇 Run (執行),然後比較您的輸出。

    Hello, World! The sum of 2 and 3 is 5. The sum of 5 and 9 is 14.
  4. 預設情況下,AWS Cloud9 會自動為您的程式碼選取執行器。若要變更執行器,請選擇 Runner (執行器),然後選擇 Python 2Python 3

    注意

    您可以為特定版本的 Python 建立自訂的執行器。如需詳細資訊,請參閱 建立建置器或執行器

步驟 4:安裝並設定 AWS SDK for Python (Boto3)

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

安裝 pip

在 AWS Cloud9 IDE 中執行 python -m pip --version 命令,確認已經為作用中的 Python 版本安裝 pip。如果已安裝 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 網站文章安裝

安裝 AWS SDK for Python (Boto3)

在您安裝 pip 後,請執行 pip install 命令來安裝 AWS SDK for Python (Boto3)。

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.

如需詳細資訊,請參閱《快速入門AWS SDK for Python (Boto3)的「安裝」一節。

在環境中設定憑證

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

若要將憑證存放在環境中,請遵循 從 AWS Cloud9 的環境呼叫 AWS 服務 中的指示,然後返回本主題。

如需詳細資訊,請參閱《》章節登入資料AWS SDK for Python (Boto3)。

步驟 5:新增 AWS SDK 程式碼

新增使用 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 程式碼

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

  2. 對於 Command (命令),輸入 s3.py my-test-bucket us-west-2,其中 my-test-bucket 是要建立的儲存貯體名稱,而 us-west-2 是建立儲存貯體的 AWS 區域 ID。預設情況下,指令碼結束之前,會先刪除您的儲存貯體。若要要保留您的儲存貯體,請將 --keep_bucket 新增到您的命令中。如需AWS區域 ID 的清單,請參AWS 一般參考.

    注意

    不只是在您的 AWS 帳戶中,Amazon S3 儲存貯體名稱在整個 AWS 中皆不可重複。

  3. 選擇 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:清除

為避免在您結束使用此教學課程後您的 AWS 帳戶仍持續產生費用,請刪除 AWS Cloud9。如需說明,請參閱 刪除 AWS Cloud9 中的環境