Python 如何使用Python中的Boto3库运行Glue Job?
问题陈述 - 使用Python中的boto3库运行Glue job,例如运行名为run_s3_file_job的作业。
阅读更多:Python 教程
解决此问题的方法/算法
步骤1 - 导入boto3和botocore exceptions以处理异常。
步骤2 - job_name是函数中的必填参数,而arguments是可选参数。有些作业需要传入参数才能运行。在这种情况下,可以将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("在run_glue_job中发生boto3客户端错误:" + e.__str__())
except Exception as e:
raise Exception("在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':'保持连接','x-amzn-requestid':
'36c48542-a060-468b-83cc-b067a540bc3c'} 'RetryAttempts':0 } }
极客教程