最近复现The artificial intelligence clinician learns optimal treatment strategies for sepsis in intensive care的论文
开个贴记录遇到的问题,我用的jupyter notebook
----------------------------------------about import psycopg2 ------------------------------------------------------
01 背景
这篇论文用到的是MIMIC-III数据库,推荐PostgreSQL管理
而psycopg2 库
是一个 PostgreSQL 数据库的 Python 客户端库,它允许 Python 程序与 PostgreSQL 数据库进行交互。它实现了 Python 数据库 API 规范 2.0(DB-API),因此可以在 Python 中进行数据库连接、执行 SQL 查询、获取查询结果等操作。
02 问题
psycopg2库导入失败:ImportError: DLL load failed while importing _psycopg: 找不到指定的模块。如下:
ImportError Traceback (most recent call last)
Cell In[1], line 1
----> 1 import psycopg2
File D:\anaconda\lib\site-packages\psycopg2\__init__.py:51
1 """A Python driver for PostgreSQL
2
3 psycopg is a PostgreSQL_ database adapter for the Python_ programming
(...)
17 TimeFromTicks, Timestamp, TimestampFromTicks
18 """
19 # psycopg/__init__.py - initialization of the psycopg module
20 #
21 # Copyright (C) 2003-2019 Federico Di Gregorio <fog@debian.org>
(...)
48
49 # Import the DBAPI-2.0 stuff into top-level module.
---> 51 from psycopg2._psycopg import ( # noqa
52 BINARY, NUMBER, STRING, DATETIME, ROWID,
53
54 Binary, Date, Time, Timestamp,
55 DateFromTicks, TimeFromTicks, TimestampFromTicks,
56
57 Error, Warning, DataError, DatabaseError, ProgrammingError, IntegrityError,
58 InterfaceError, InternalError, NotSupportedError, OperationalError,
59
60 _connect, apilevel, threadsafety, paramstyle,
61 __version__, __libpq_version__,
62 )
65 # Register default adapters.
67 from psycopg2 import extensions as _ext
ImportError: DLL load failed while importing _psycopg: 找不到指定的模块
03 解决办法
分析:
(1)这个错误通常是由于 psycopg2
模块无法找到相关的依赖项,其中最常见的依赖项是 PostgreSQL 客户端库 libpq
。解决这个问题的方法通常是安装 PostgreSQL 客户端库,或者将其路径添加到系统的环境变量中。
(2)python 版本和 psycopg2版本不匹配
推荐解决办法:
step1:将PostgreSQL的路径添加到系统的环境变量中
具体如下:
在 Windows 操作系统中,将 libpq
的路径添加到系统的环境变量中,可以通过以下步骤实现:
-
找到 libpq 库的路径: 通常情况下,PostgreSQL 安装后会包含
libpq.dll
这个文件。你可以在 PostgreSQL 的安装目录中找到它。默认情况下,它位于C:\Program Files\PostgreSQL\<version>\bin
目录下,其中<version>
是你安装的 PostgreSQL 版本号。 -
将 libpq 路径添加到环境变量:
- 右键点击此电脑(或者我的电脑),然后选择 "属性"。
- 在系统窗口中,选择 "高级系统设置"。
- 在弹出的窗口中选择 "环境变量"。
- 在 "系统变量" 部分,找到名为 "Path" 的变量,并双击打开。
- 在变量值的末尾添加 PostgreSQL 安装目录下
bin
文件夹的路径(例如:C:\Program Files\PostgreSQL\<version>\bin
),用分号;
分隔。 - 确认所有对话框并关闭窗口。
-
重新启动 Jupyter Notebook 或者 Python 环境: 确保重启后环境变量的更改生效。
step 2 :如果还没解决,可能是psycopg2版本不对
1.卸载已经下载的库,(此时可以看到之前装的库版本,我的是2.9.9)
pip install --upgrade psycopg2
如下
2.根据自己的python版本重新安装,我的python是3.8.17,对应安装2.8.6的psycopg2可行(其他版本可以从下文链接里找)
重新下载指定版本
pip install psycopg2==2.8.6
pip install psycopg2-binary==2.8.6
step 3 :重启jupyter notebook,看是否解决
解决!
===================================================================
关于这个问题的更详细解答、python版本对应的库可以在这个文章里找到
https://stackoverflow.com/questions/64314141/psycopg2-importerror-dll-load-failed-while-importing-psycopg-the-operating