gpt4 book ai didi

python - PostgreSQL-ModuleNotFoundError : No module named 'psycopg2'

转载 作者:行者123 更新时间:2023-12-02 07:47:55 29 4
gpt4 key购买 nike

我可以确认 psycopg2 已安装(使用 conda install -c anaconda psycopg2),但 psycopg2 似乎无法导入到我的 python 脚本中,或者解释器无法找到它。我还尝试使用 pip3 安装,满足要求,这意味着 psycopg2 已经安装,但无法理解为什么我的脚本无法导入它。使用Mac(操作系统v10.14.4)

$ python create_tables.py
Traceback (most recent call last):
File "create_tables.py", line 1, in <module>
import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

$ pip3 install psycopg2
Requirement already satisfied: psycopg2 in /usr/local/lib/python3.7/site-packages (2.8.2)
$ pip3 install psycopg2-binary
Requirement already satisfied: psycopg2-binary in /usr/local/lib/python3.7/site-packages (2.8.2)
python -V
Python 3.7.0

知道为什么会发生这种情况吗?

编辑: create_table.py

import psycopg2
from config import config


def create_tables():
""" create tables in the PostgreSQL database"""
commands = (
"""
CREATE TABLE vendors (
vendor_id SERIAL PRIMARY KEY,
vendor_name VARCHAR(255) NOT NULL
)
""",
""" CREATE TABLE parts (
part_id SERIAL PRIMARY KEY,
part_name VARCHAR(255) NOT NULL
)
""",
"""
CREATE TABLE part_drawings (
part_id INTEGER PRIMARY KEY,
file_extension VARCHAR(5) NOT NULL,
drawing_data BYTEA NOT NULL,
FOREIGN KEY (part_id)
REFERENCES parts (part_id)
ON UPDATE CASCADE ON DELETE CASCADE
)
""",
"""
CREATE TABLE vendor_parts (
vendor_id INTEGER NOT NULL,
part_id INTEGER NOT NULL,
PRIMARY KEY (vendor_id , part_id),
FOREIGN KEY (vendor_id)
REFERENCES vendors (vendor_id)
ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (part_id)
REFERENCES parts (part_id)
ON UPDATE CASCADE ON DELETE CASCADE
)
""")
conn = None
try:
# read the connection parameters
params = config()
# connect to the PostgreSQL server
conn = psycopg2.connect(**params)
cur = conn.cursor()
# create table one by one
for command in commands:
cur.execute(command)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()


if __name__ == '__main__':
create_tables()

最佳答案

是的,找到了解决方案,

python -m pip install psycopg2-binary 

成功了!

关于python - PostgreSQL-ModuleNotFoundError : No module named 'psycopg2' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755095/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com