如何导入ETL脚本中引用的文件?

chr*_*non 5 pyspark aws-glue

我有一个脚本,我想将配置文件传递到其中。在 Glue 作业页面上,我看到有一个“引用文件路径”指向我的配置文件。然后如何在我的 ETL 脚本中使用该文件?

我已经尝试过from configuration import *,其中引用的文件名是configuration.py,但没有运气(导入错误:没有名为配置的模块)。

Ibr*_*kin 4

我注意到同样的问题。我相信已经有一张票可以解决这个问题,但以下是 AWS 支持人员同时提出的建议。

如果您在Python shell作业中使用引用的文件路径变量,则在 中找到引用的文件,其中 Python shell 作业默认无访问权限。但是,相同的操作在 Spark 作业中可以成功执行,因为该文件是在默认文件目录中找到的。/tmp

sample_config.json下面的代码有助于查找Glue 作业配置中引用的绝对路径并打印其内容。

import json
import sys, os

def get_referenced_filepath(file_name, matchFunc=os.path.isfile):
    for dir_name in sys.path:
        candidate = os.path.join(dir_name, file_name)
        if matchFunc(candidate):
            return candidate
    raise Exception("Can't find file: ".format(file_name))

with open(get_referenced_filepath('sample_config.json'), "r") as f:
    data = json.load(f)
    print(data)
Run Code Online (Sandbox Code Playgroud)

Boto3 API 也可用于访问引用的文件

import boto3

s3 = boto3.resource('s3')
obj = s3.Object('sample_bucket', 'sample_config.json')
for line in obj.get()['Body']._raw_stream:
    print(line)
Run Code Online (Sandbox Code Playgroud)