适用于 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 代码与 Amazon S3 等 AWS 服务进行交互。例如,您可以使用开发工具包创建 Amazon S3 存储桶,列出您的可用存储桶,然后删除刚刚创建的存储桶。

安装 pip

在 AWS Cloud9 IDE 中,通过运行 python -m pip --version 命令确认 pip 是否已经安装 Python 的活动版本。如果已安装 pip,请跳到下一节。

要安装 pip,请运行以下命令。由于 sudo 与用户处于不同的环境中,因此,如果 Python 的版本与当前别名版本不同,则必须指定要使用的 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 服务时,都必须提供一组凭证才能进行调用。这些凭证确定开发工具包是否具有必需的权限以进行调用。如果凭证没有包括必需的权限,调用将失败。

要在环境中存储凭证,请按照 从 AWS Cloud9 中的环境调用 AWS 服务 中的说明进行操作,然后返回到该主题。

有关其他信息,请参阅 中的凭证AWS SDK for Python (Boto3)。

步骤 5:添加 AWS 开发工具包代码

添加代码,该代码使用 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 开发工具包代码

  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 一般参考》中的 Amazon Simple Storage Service Endpoints and Quotas

    注意

    Amazon S3 存储桶名称在整个 AWS 中都必须是唯一的,而不仅仅在您的 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 中删除环境