

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# EMR Notebooks 的示例编程命令
<a name="emr-managed-notebooks-headless"></a>

## 概述
<a name="emr-managed-notebooks-headless-overview"></a>

您可以通过脚本或命令行执行 APIs 来执行 EMR 笔记本。当您在 AWS 控制台之外启动、停止、列出和描述 EMR 笔记本执行时，您可以通过编程方式控制 EMR 笔记本。您可以将不同的参数值传递给带参数化 Notebook 单元格的 Notebook。这样就不必为每组新参数值创建 Notebook 副本。有关更多信息，请参阅 [Amazon EMR API actions](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)。

您可以通过Amazon CloudWatch 事件安排或批量执行EMR笔记本和. AWS Lambda有关更多信息，请参阅[AWS Lambda 与 Amazon CloudWatch 活动配合使用](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents.html)。

**注意**  
EMR Notebooks 在控制台中作为 Amazon EMR Studio Workspaces 提供。通过控制台中的**创建 Workspace** 按钮，可以创建新的 Notebooks。要访问或创建 Workspaces，EMR Notebooks 用户需要额外的 IAM 角色权限。有关更多信息，请参阅 [Amazon EMR Notebooks 是控制台中的 Amazon EMR Studio Workspaces](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 和 [Amazon EMR 控制台](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)。

## 编程执行的角色权限
<a name="emr-managed-notebooks-headless-permissions"></a>

要在 EMR Notebooks 中使用编程执行，您必须使用以下策略配置用户权限：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowExecutionActions",
      "Effect": "Allow",
      "Action": [
        "elasticmapreduce:StartNotebookExecution",
        "elasticmapreduce:DescribeNotebookExecution",
        "elasticmapreduce:ListNotebookExecutions"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Sid": "AllowPassingServiceRole",
      "Effect": "Allow",
      "Action": [
        "iam:PassRole"
      ],
      "Resource": [
        "arn:aws:iam::123456789012:role/EMR_Notebooks_DefaultRole"
      ]
    }
  ]
}
```

------

在 EMR Notebooks 集群上以编程方式执行 EMR Notebooks 时，您必须添加以下额外权限：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowRetrievingManagedEndpointCredentials",
      "Effect": "Allow",
      "Action": [
        "emr-containers:GetManagedEndpointSessionCredentials"
      ],
      "Resource": [
        "arn:aws:emr-containers:*:123456789012:/virtualclusters/virtual-cluster-id/endpoints/managed-endpoint-id"
      ],
      "Condition": {
        "StringEquals": {
          "emr-containers:ExecutionRoleArn": [
            "arn:aws:iam::123456789012:role/emr-on-eks-execution-role"
          ]
        }
      }
    },
    {
      "Sid": "AllowDescribingManagedEndpoint",
      "Effect": "Allow",
      "Action": [
        "emr-containers:DescribeManagedEndpoint"
      ],
      "Resource": [
        "arn:aws:emr-containers:*:123456789012:/virtualclusters/virtual-cluster-id/endpoints/managed-endpoint-id"
      ]
    }
  ]
}
```

------

## 编程执行的限制
<a name="emr-managed-notebooks-headless-limit"></a>
+ 每个 AWS 区域 账户最多支持 100 个并发执行。
+ 如果运行超过 30 天，则会终止执行。
+ Amazon EMR Serverless 交互式应用程序不支持以编程方式执行 Notebooks 电脑实例。

## 编程 EMR Notebook 执行示例
<a name="emr-managed-notebooks-headless-examples"></a>

以下各节提供了使用 AWS CLI、Boto3 SDK (Python) 和 Ruby 以编程方式执行 EMR 笔记本的几个示例：
+ [EMR Studio 中的 Notebook CLI 命令示例](emr-managed-notebooks-headless-cli.md)
+ [EMR Notebook 的 Python 示例](emr-managed-notebooks-headless-python.md)
+ [EMR Notebook 的 Ruby 示例](emr-managed-notebooks-headless-ruby.md)

您还可以使用编排工具 [例如 Apache Airflow 或 Amazon Managed Workflows for Apache Airflow（MWAA）]，将参数化 Notebooks 作为计划工作流的一部分运行。有关更多信息，请参阅AWS 大数据博客中的 [Orchestrating analytics jobs on EMR Notebooks using MWAA](https://aws.amazon.com/blogs/big-data/orchestrating-analytics-jobs-on-amazon-emr-notebooks-using-amazon-mwaa/)。**

# EMR Studio 中的 Notebook CLI 命令示例
<a name="emr-managed-notebooks-headless-cli"></a>

本主题显示了 EMR Notebook 的 CLI 命令示例。该示例使用 EMR Notebooks 控制台中的演示 Notebook。要查找 Notebook，请使用相对于主目录的文件路径。在此示例中，您可以运行两个 Notebook 文件：`demo_pyspark.ipynb` 和 `my_folder/python3.ipynb`。

**注意**  
EMR Notebooks 在控制台中作为 Amazon EMR Studio Workspaces 提供。通过控制台中的**创建 Workspace** 按钮，可以创建新的 Notebooks。要访问或创建 Workspaces，EMR Notebooks 用户需要额外的 IAM 角色权限。有关更多信息，请参阅 [Amazon EMR Notebooks 是控制台中的 Amazon EMR Studio Workspaces](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 和 [Amazon EMR 控制台](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)。

文件 `demo_pyspark.ipynb` 的相对路径是 `demo_pyspark.ipynb`，如下所示。

![\[Jupyter notebook interface showing a file explorer and code editor with PySpark content.\]](http://docs.aws.amazon.com/zh_cn/emr/latest/ManagementGuide/images/notebook_exe_folder_structure_1.png)


`python3.ipynb` 的相对路径是 `my_folder/python3.ipynb`，如下所示。

![\[File explorer showing python3.ipynb in my_folder, and Jupyter notebook interface with code.\]](http://docs.aws.amazon.com/zh_cn/emr/latest/ManagementGuide/images/notebook_exe_folder_structure_2.png)


有关 Amazon EMR API `NotebookExecution` 操作的更多信息，请参阅 [Amazon EMR API actions](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)。

## 运行 Notebook
<a name="emr-managed-notebooks-api-actions"></a>

您可以使用 AWS CLI 来运行带有`start-notebook-execution`操作的笔记本，如以下示例所示。

**Example ：使用（运行在 Amazon EC2 上的）Amazon EMR 集群在 EMR Studio Workspace 中执行 EMR Notebook。**  

```
aws emr --region us-east-1 \
start-notebook-execution \
--editor-id e-ABCDEFG123456 \
--notebook-params '{"input_param":"my-value", "good_superhero":["superman", "batman"]}' \
--relative-path test.ipynb \
--notebook-execution-name my-execution \
--execution-engine '{"Id" : "j-1234ABCD123"}' \
--service-role EMR_Notebooks_DefaultRole 
 
{
    "NotebookExecutionId": "ex-ABCDEFGHIJ1234ABCD"
}
```

**Example ：使用 EMR Notebooks 集群在 EMR Studio Workspace 中执行 EMR Notebook。**  

```
aws emr start-notebook-execution \
    --region us-east-1 \
    --service-role EMR_Notebooks_DefaultRole \
    --environment-variables '{"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.executor.instances=1", "KERNEL_LAUNCH_TIMEOUT": "350"}' \
    --output-notebook-format HTML \
    --execution-engine Id=arn:aws:emr-containers:us-west-2:account-id:/virtualclusters/ABCDEFG/endpoints/ABCDEF,Type=EMR_ON_EKS,ExecutionRoleArn=arn:aws:iam::account-id:role/execution-role \
    --editor-id e-ABCDEFG \
    --relative-path EMRonEKS-spark_python.ipynb
```

**Example ：执行 EMR Notebook 来指定其 Amazon S3 位置**  

```
aws emr start-notebook-execution \
    --region us-east-1 \
    --notebook-execution-name my-execution-on-emr-on-eks-cluster \
    --service-role EMR_Notebooks_DefaultRole \
    --environment-variables '{"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.executor.instances=1", "KERNEL_LAUNCH_TIMEOUT": "350"}' \
    --output-notebook-format HTML \
    --execution-engine Id=arn:aws:emr-containers:us-west-2:account-id:/virtualclusters/ABCDEF/endpoints/ABCDEF,Type=EMR_ON_EKS,ExecutionRoleArn=arn:aws:iam::account-id:role/execution-role \
    --notebook-s3-location '{"Bucket": "amzn-s3-demo-bucket","Key": "s3-prefix-to-notebook-location/EMRonEKS-spark_python.ipynb"}' \
    --output-notebook-s3-location '{"Bucket": "amzn-s3-demo-bucket","Key": "s3-prefix-for-storing-output-notebook"}'
```

## Notebook 输出
<a name="emr-managed-notebooks-headless-cli-output"></a>

 下面是示例 Notebook 的输出内容。单元格 3 显示新注入的参数值。

![\[Jupyter notebook cells showing Python code and output for parameter injection and manipulation.\]](http://docs.aws.amazon.com/zh_cn/emr/latest/ManagementGuide/images/HelloWorld_notebook.png)


## 描述 Notebook
<a name="emr-managed-notebooks-headless-cli-describe"></a>

您可以使用 `describe-notebook-execution` 操作以访问关于特定 Notebook 执行的信息。

```
aws emr --region us-east-1 \
describe-notebook-execution --notebook-execution-id ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE
 
{
    "NotebookExecution": {
        "NotebookExecutionId": "ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
        "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
        "ExecutionEngine": {
            "Id": "j-2QMOV6JAX1TS2",
            "Type": "EMR",
            "MasterInstanceSecurityGroupId": "sg-05ce12e58cd4f715e"
        },
        "NotebookExecutionName": "my-execution",
        "NotebookParams": "{\"input_param\":\"my-value\", \"good_superhero\":[\"superman\", \"batman\"]}",
        "Status": "FINISHED",
        "StartTime": 1593490857.009,
        "Arn": "arn:aws:elasticmapreduce:us-east-1:123456789012:notebook-execution/ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
        "LastStateChangeReason": "Execution is finished for cluster j-2QMOV6JAX1TS2.",
        "NotebookInstanceSecurityGroupId": "sg-0683b0a39966d4a6a",
        "Tags": []
    }
}
```

## 停止运行 Notebook
<a name="emr-managed-notebooks-headless-cli-stop"></a>

如果您想要停止 Notebook 正在运行的执行，您可以借助 `stop-notebook-execution` 命令。

```
# stop a running execution
aws emr --region us-east-1 \
stop-notebook-execution --notebook-execution-id ex-IZWZX78UVPAATC8LHJR129B1RBN4T
 
 
# describe it
aws emr --region us-east-1 \
describe-notebook-execution --notebook-execution-id ex-IZWZX78UVPAATC8LHJR129B1RBN4T
 
{
    "NotebookExecution": {
        "NotebookExecutionId": "ex-IZWZX78UVPAATC8LHJR129B1RBN4T",
        "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
        "ExecutionEngine": {
            "Id": "j-2QMOV6JAX1TS2",
            "Type": "EMR"
        },
        "NotebookExecutionName": "my-execution",
        "NotebookParams": "{\"input_param\":\"my-value\", \"good_superhero\":[\"superman\", \"batman\"]}",
        "Status": "STOPPED",
        "StartTime": 1593490876.241,
        "Arn": "arn:aws:elasticmapreduce:us-east-1:123456789012:editor-execution/ex-IZWZX78UVPAATC8LHJR129B1RBN4T",
        "LastStateChangeReason": "Execution is stopped for cluster j-2QMOV6JAX1TS2. Internal error",
        "Tags": []
    }
}
```

## 按开启时间列出 Notebook 的执行情况
<a name="emr-managed-notebooks-headless-cli-list"></a>

您可以将 `--from` 参数输入至 `list-notebook-executions`，按开启时间列出 Notebook 的执行情况。

```
# filter by start time 
aws emr --region us-east-1 \ 
list-notebook-executions --from 1593400000.000
 
{
    "NotebookExecutions": [
        {
            "NotebookExecutionId": "ex-IZWZX78UVPAATC8LHJR129B1RBN4T",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "STOPPED",
            "StartTime": 1593490876.241
        },
        {
            "NotebookExecutionId": "ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "RUNNING",
            "StartTime": 1593490857.009
        },
        {
            "NotebookExecutionId": "ex-IZWZYRS0M14L5V95WZ9OQ399SKMNW",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "STOPPED",
            "StartTime": 1593490292.995
        },
        {
            "NotebookExecutionId": "ex-IZX009ZK83IVY5E33VH8MDMELVK8K",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FINISHED",
            "StartTime": 1593489834.765
        },
        {
            "NotebookExecutionId": "ex-IZWZXOZF88JWDF9J09GJ91R57VI0N",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FAILED",
            "StartTime": 1593488934.688
        }
    ]
}
```

## 按开启时间和状态列出 Notebook 的执行情况
<a name="emr-managed-notebooks-headless-cli-list"></a>

`list-notebook-executions` 命令也可以采用 `--status` 参数来筛选结果。

```
# filter by start time and status 
aws emr --region us-east-1 \                 
list-notebook-executions --from 1593400000.000 --status FINISHED
{
    "NotebookExecutions": [
        {
            "NotebookExecutionId": "ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FINISHED",
            "StartTime": 1593490857.009
        },
        {
            "NotebookExecutionId": "ex-IZX009ZK83IVY5E33VH8MDMELVK8K",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FINISHED",
            "StartTime": 1593489834.765
        }
    ]
}
```

# EMR Notebook 的 Python 示例
<a name="emr-managed-notebooks-headless-python"></a>

本主题包含一个示例命令文件。代码示例是一个名为 `demo.py` 的 SDK for Python（Boto3）文件。它显示了笔记本的执行情况 APIs。

**注意**  
EMR Notebooks 在控制台中作为 Amazon EMR Studio Workspaces 提供。通过控制台中的**创建 Workspace** 按钮，可以创建新的 Notebooks。要访问或创建 Workspaces，EMR Notebooks 用户需要额外的 IAM 角色权限。有关更多信息，请参阅 [Amazon EMR Notebooks 是控制台中的 Amazon EMR Studio Workspaces](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 和 [Amazon EMR 控制台](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)。

有关 Amazon EMR API `NotebookExecution` 操作的更多信息，请参阅 [Amazon EMR API actions](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)。

```
import boto3,time

emr = boto3.client(
    'emr',
    region_name='us-west-1'
)     
     
start_resp = emr.start_notebook_execution(
    EditorId='e-40AC8ZO6EGGCPJ4DLO48KGGGI',
    RelativePath='boto3_demo.ipynb',
    ExecutionEngine={'Id':'j-1HYZS6JQKV11Q'},
    ServiceRole='EMR_Notebooks_DefaultRole'
)

execution_id = start_resp["NotebookExecutionId"]
print(execution_id)
print("\n")
     
describe_response = emr.describe_notebook_execution(NotebookExecutionId=execution_id)
     
print(describe_response)
print("\n")
     
list_response = emr.list_notebook_executions()
print("Existing notebook executions:\n")
for execution in list_response['NotebookExecutions']:
    print(execution)
    print("\n")  
     
print("Sleeping for 5 sec...")
time.sleep(5)
     
print("Stop execution " + execution_id)
emr.stop_notebook_execution(NotebookExecutionId=execution_id)
describe_response = emr.describe_notebook_execution(NotebookExecutionId=execution_id)
print(describe_response)
print("\n")
```

下面是运行 `demo.py` 的输出。

```
ex-IZX56YJDW1D29Q1PHR32WABU2SAPK
     
{'NotebookExecution': {'NotebookExecutionId': 'ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'ExecutionEngine': {'Id': 'j-1HYZS6JQKV11Q', 'Type': 'EMR'}, 'NotebookExecutionName': '', 'Status': 'STARTING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 49, 19, 418000, tzinfo=tzlocal()), 'Arn': 'arn:aws:elasticmapreduce:us-west-1:123456789012:notebook-execution/ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'LastStateChangeReason': 'Execution is starting for cluster j-1HYZS6JQKV11Q.', 'Tags': []}, 'ResponseMetadata': {'RequestId': '70f12c5f-1dda-45b7-adf6-964987d373b7', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '70f12c5f-1dda-45b7-adf6-964987d373b7', 'content-type': 'application/x-amz-json-1.1', 'content-length': '448', 'date': 'Wed, 19 Aug 2020 00:49:22 GMT'}, 'RetryAttempts': 0}}
     
Existing notebook executions:
     
{'NotebookExecutionId': 'ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'STARTING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 49, 19, 418000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5ABS5PR1E5AHMFYEMX3JJIORRB', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'RUNNING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 48, 36, 373000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5GLVXIU1HNI8BWVW057F6MF4VE', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 45, 14, 646000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 46, 26, 543000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5CV8YDUO8JAIWMXN2VH32RUIT1', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 43, 5, 807000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 44, 31, 632000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5AS0PPW55CEDEURZ9NSOWSUJZ6', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 42, 29, 265000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 43, 48, 320000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX57YF5Q53BKWLR4I5QZ14HJ7DRS', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 38, 37, 81000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 40, 39, 646000, tzinfo=tzlocal())}
     
Sleeping for 5 sec...
Stop execution ex-IZX56YJDW1D29Q1PHR32WABU2SAPK
{'NotebookExecution': {'NotebookExecutionId': 'ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'ExecutionEngine': {'Id': 'j-1HYZS6JQKV11Q', 'Type': 'EMR'}, 'NotebookExecutionName': '', 'Status': 'STOPPING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 49, 19, 418000, tzinfo=tzlocal()), 'Arn': 'arn:aws:elasticmapreduce:us-west-1:123456789012:notebook-execution/ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'LastStateChangeReason': 'Execution is being stopped for cluster j-1HYZS6JQKV11Q.', 'Tags': []}, 'ResponseMetadata': {'RequestId': '2a77ef73-c1c6-467c-a1d1-7204ab2f6a53', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '2a77ef73-c1c6-467c-a1d1-7204ab2f6a53', 'content-type': 'application/x-amz-json-1.1', 'content-length': '453', 'date': 'Wed, 19 Aug 2020 00:49:30 GMT'}, 'RetryAttempts': 0}}
```

# EMR Notebook 的 Ruby 示例
<a name="emr-managed-notebooks-headless-ruby"></a>

本主题包含一个演示 Notebook 功能的 Ruby 示例。

**注意**  
EMR Notebooks 在控制台中作为 Amazon EMR Studio Workspaces 提供。通过控制台中的**创建 Workspace** 按钮，可以创建新的 Notebooks。要访问或创建 Workspaces，EMR Notebooks 用户需要额外的 IAM 角色权限。有关更多信息，请参阅 [Amazon EMR Notebooks 是控制台中的 Amazon EMR Studio Workspaces](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 和 [Amazon EMR 控制台](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)。

以下 Ruby 代码示例演示了如何使用 Notebook 执行 API。

```
# prepare an Amazon EMR client

emr = Aws::EMR::Client.new(
  region: 'us-east-1',
  access_key_id: 'AKIA...JKPKA',
  secret_access_key: 'rLMeu...vU0OLrAC1',
)
```

## 启动 Notebook 执行并获取执行 ID
<a name="emr-managed-notebooks-headless-ruby-startretrieve"></a>

在此示例中，Amazon S3 编辑器和 EMR Notebook 是 `s3://amzn-s3-demo-bucket/notebooks/e-EA8VGAA429FEQTC8HC9ZHWISK/test.ipynb`。

有关 Amazon EMR API `NotebookExecution` 操作的更多信息，请参阅 [Amazon EMR API actions](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)。

```
start_response = emr.start_notebook_execution({
    editor_id: "e-EA8VGAA429FEQTC8HC9ZHWISK",
    relative_path: "test.ipynb",
    
    execution_engine: {id: "j-3U82I95AMALGE"},
    
    service_role: "EMR_Notebooks_DefaultRole",
})


notebook_execution_id = start_resp.notebook_execution_id
```

## 描述 Notebook 执行并打印详细信息
<a name="emr-managed-notebooks-headless-ruby-describeprint"></a>

```
describe_resp = emr.describe_notebook_execution({
    notebook_execution_id: notebook_execution_id
})
puts describe_resp.notebook_execution
```

上述命令的输出如下。

```
{
:notebook_execution_id=>"ex-IZX3VTVZWVWPP27KUB90BZ7V9IEDG", 
:editor_id=>"e-EA8VGAA429FEQTC8HC9ZHWISK",
:execution_engine=>{:id=>"j-3U82I95AMALGE", :type=>"EMR", :master_instance_security_group_id=>nil}, 
:notebook_execution_name=>"", 
:notebook_params=>nil, 
:status=>"STARTING", 
:start_time=>2020-07-23 15:07:07 -0700, 
:end_time=>nil, 
:arn=>"arn:aws:elasticmapreduce:us-east-1:123456789012:notebook-execution/ex-IZX3VTVZWVWPP27KUB90BZ7V9IEDG", 
:output_notebook_uri=>nil, 
:last_state_change_reason=>"Execution is starting for cluster j-3U82I95AMALGE.", :notebook_instance_security_group_id=>nil, 
:tags=>[]
}
```

## Notebook 筛选条件
<a name="emr-managed-notebooks-headless-ruby-filters"></a>

```
"EditorId": "e-XXXX",           [Optional]
"From" : "1593400000.000",    [Optional]
"To" :
```

### 停止 Notebook 执行
<a name="emr-managed-notebooks-headless-ruby-stop"></a>

```
stop_resp = emr.stop_notebook_execution({
    notebook_execution_id: notebook_execution_id
})
```