

 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단계: 설치 및 구성 AWS SDK for Python (Boto3)](#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>

이 자습서를 사용하기 전에 다음 요구 사항을 충족하는지 확인하십시오.
+ ** AWS Cloud9 EC2 개발 환경이 있는 경우**

  이 샘플에서는 Amazon Linux 또는 Ubuntu 서버를 실행 중인 Amazon EC2 인스턴스에 연결된 EC2 환경이 이미 있다고 가정합니다. 세부 정보는 [EC2 환경 생성](create-environment-main.md) 섹션을 참조하세요.

  다른 유형의 환경 또는 운영 체제가 있다면 이 자습서의 지침을 적용해야 합니다.
+ **해당 환경에 대한 AWS Cloud9 IDE를 열었습니다.**

  환경을 열면가 웹 브라우저에서 해당 환경의 IDE를 AWS Cloud9 엽니다. 세부 정보는 [에서 환경 열기 AWS Cloud9](open-environment.md) 섹션을 참조하세요.

## 1단계: Python 설치
<a name="sample-python-install"></a>

1.  AWS Cloud9 IDE의 터미널 세션에서 ** `python --version` ** 명령을 실행하여 Python이 이미 설치되어 있는지 확인합니다. (새 터미널 세션을 시작하려면 메뉴 모음에서 **창**, **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. **실행**을 선택하여 출력을 비교합니다.

   ```
   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단계: 설치 및 구성 AWS SDK for Python (Boto3)
<a name="sample-python-sdk"></a>

 AWS SDK for Python (Boto3) 를 사용하면 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/)를 참조하세요.

### 설치 AWS SDK for Python (Boto3)
<a name="sample-python-sdk-install-sdk"></a>

를 설치한 후 ** `pip install` ** 명령을 실행 AWS SDK for Python (Boto3) 하여를 `pip`설치합니다.

```
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)의 [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)(빠른 시작)에서 "설치" 섹션을 참조하세요.

### 환경에서 자격 증명 설정
<a name="sample-python-sdk-credentials"></a>

를 사용하여 AWS 서비스를 호출 AWS SDK for Python (Boto3) 할 때마다 호출과 함께 자격 증명 세트를 제공해야 합니다. 이러한 자격 증명은 SDK에 호출을 수행하는 데 필요한 권한이 있는지 여부를 결정합니다. 자격 증명이 필요한 권한을 포함하지 않으면 호출이 실패합니다.

환경에 자격 증명을 저장하려면 [AWS 서비스 의 환경에서 호출 AWS Cloud9](credentials.md)의 지침을 따른 다음 이 주제로 돌아옵니다.

자세한 내용은 AWS SDK for Python (Boto3)에서 [자격 증명](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html)을 참조하세요.

## 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. 메뉴 표시줄에서 **실행**, **실행 구성**, **새 실행 구성**을 선택합니다.

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) 단원을 참조하세요.