如何在Python中使用Boto3库运行Glue作业?


问题陈述 − 使用Python中的boto3库运行Glue作业。例如,运行作业run_s3_file_job。

解决此问题的方案/算法

步骤1 − 导入boto3和botocore异常以处理异常。

步骤2 − job_name是函数中的必填参数,而arguments是可选参数。一些作业需要参数才能运行。在这种情况下,参数可以作为字典传递。

例如:arguments = {‘arguments1’ = ‘value1’, ‘arguments2’ = ‘value2’}

如果作业不需要参数,则只需传递job_name。

步骤3 − 使用boto3库创建一个AWS会话。确保在默认配置文件中提到了region_name。如果没有提到,则在创建会话时显式传递region_name。

步骤4 − 为Glue创建一个AWS客户端。

步骤5 − 现在使用start_job_run函数并根据需要传递JobName和arguments。

步骤6 − 作业启动后,它将使用作业的元数据提供job_run_id。

步骤7 − 如果在检查作业时出现问题,请处理通用异常。

示例

使用以下代码运行现有的Glue作业:

import boto3
from botocore.exceptions import ClientError

def run_glue_job(job_name, arguments = {}):
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      job_run_id = glue_client.start_job_run(JobName=job_name, Arguments=arguments)
   return job_run_id
   except ClientError as e:
      raise Exception( "boto3 client error in run_glue_job: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in run_glue_job: " + e.__str__())

print(run_glue_job("run_s3_file_job"))

输出

{'JobRunId':
'jr_5f8136286322ce5b7d0387e28df6742abc6f5e6892751431692ffd717f45fc00',
'ResponseMetadata': {'RequestId': '36c48542-a060-468b-83ccb067a540bc3c', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 13
Feb 2021 13:36:50 GMT', 'content-type': 'application/x-amz-json-1.1',
'content-length': '82', 'connection': 'keep-alive', 'x-amzn-requestid':
'36c48542-a060-468b-83cc-b067a540bc3c'}, 'RetryAttempts': 0}}

更新于:2021年3月22日

2K+ 浏览量

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.