AWS Glue中使用psycopg2遇ModuleNotFoundError问题求助
解决AWS Glue中psycopg2的ModuleNotFoundError: No module named 'psycopg2._psycopg'问题
核心原因
psycopg2是依赖C扩展的PostgreSQL客户端库,AWS Glue的执行环境基于Amazon Linux,pip默认安装的预编译包(包括psycopg2-binary)可能与环境中的系统库版本不兼容,导致C扩展模块_psycopg无法加载。
可行解决方案
方案1:使用Glue原生JDBC连接PostgreSQL(推荐)
放弃使用psycopg2,改用Glue官方支持的JDBC方式连接PostgreSQL,完全避开第三方模块兼容性问题:
# 示例:用Spark JDBC读取PostgreSQL数据 url = "jdbc:postgresql://your-postgres-host:5432/your-db" properties = { "user": "your-username", "password": "your-password", "driver": "org.postgresql.Driver" } df = spark.read.jdbc(url=url, table="your-table", properties=properties) # 示例:用Glue DynamicFrame读取 from awsglue.context import GlueContext glueContext = GlueContext(spark.sparkContext) dynamic_frame = glueContext.create_dynamic_frame.from_options( connection_type="postgresql", connection_options={ "url": url, "dbtable": "your-table", "user": "your-username", "password": "your-password" } )
注意:需要确保Glue作业角色有访问PostgreSQL实例的权限(如VPC网络打通、安全组放行)。
方案2:编译适配Glue环境的psycopg2 wheel包
如果必须使用psycopg2,需要在与Glue环境一致的Amazon Linux 2系统中编译对应的wheel包:
- 启动一台Amazon Linux 2 EC2实例,安装对应Glue版本的Python(Glue 2.0用Python 3.7,Glue 3.0用Python 3.8)。
- 安装编译依赖:
sudo yum install -y postgresql-devel gcc python3-devel - 创建虚拟环境并编译生成wheel包:
python3 -m venv venv source venv/bin/activate pip install wheel pip wheel psycopg2==2.9.3 -w ./dist - 将生成的
psycopg2-2.9.3-cp37-cp37m-linux_x86_64.whl(对应Python 3.7)上传到S3存储桶。 - 在Glue作业配置中,将
--additional-python-modules设置为s3://your-bucket/path/to/psycopg2-xxx.whl,同时添加--python-modules-installer-option="--no-cache-dir"避免缓存干扰。
方案3:指定兼容版本的psycopg2-binary
尝试使用与Glue Python版本严格兼容的psycopg2-binary版本,比如针对Glue 2.0(Python 3.7)和3.0(Python 3.8)都可以用psycopg2-binary==2.9.3:
在Glue作业的附加参数中设置:
--additional-python-modules psycopg2-binary==2.9.3 --python-modules-installer-option="--no-cache-dir"
注意:部分情况下仍可能因系统库不兼容失败,此时优先选择方案1或2。
内容的提问来源于stack exchange,提问作者Dipanshu Chaubey
相关产品推荐
相关产品推荐

