我对导入顺序和使用感到困惑。 正如您在下面的代码中看到的那样,首先,我首先导入psycopg2。 然后我导入data_connect(依赖于psycopg2),所以有两个问题: (1)为什么解释器看不到我已经导入了psycopg2? (2)如何解决? 谢谢!
错误消息:
File "C:\home\partscobra.com\wwwroot\data_connect.py" in data_connect:
db_conn = psycopg2.connect(...
NameError: name 'psycopg2' is not defined"
main.py:
import psycopg2
from data_connect import data_connect, data_cursor
#error here
[snip]
data_connect.py:
def data_connect():
t_host = "blahblahblah"
t_port = "5432"
t_dbname = "inventory"
t_user = "remote"
t_pw = "blahblahblah"
db_conn = psycopg2.connect(
host=t_host,
port=t_port,
dbname=t_dbname,
user=t_user,
password=t_pw
)
db_conn.autocommit=True
return db_conn
def data_cursor():
db_conn = data_connect()
db_cursor = db_conn.cursor()
return db_cursor
答案 0 :(得分:3)
您导入的内容将添加到当前名称空间(在这种情况下为main
模块的全局名称空间),而不是每个模块(例如data_connect
)。
如果您在import psycopg2
中data_connect.py
,则psycopg2
将被添加到data_connect
模块的全局命名空间中。