python,从def访问psycopg2?
我试图在一个文件中创建一组 defs,这样每当我想在 python 中创建脚本时我就可以导入它们
我已经尝试过:
def get_dblink( dbstring):
"""
Return a database cnx.
"""
global psycopg2
try
cnx = psycopg2.connect( dbstring)
except Exception, e:
print "Unable to connect to DB. Error [%s]" % ( e,)
exit( )
但我收到此错误:全局名称“psycopg2”未
在我的文件中 主文件 script.py
定义我有
import psycopg2, psycopg2.extras
from misc_defs import *
hostname = '192.168.10.36'
database = 'test'
username = 'test'
password = 'test'
dbstring = "host='%s' dbname='%s' user='%s' password='%s'" % ( hostname, database, username, password)
cnx = get_dblink( dbstring)
:有人可以帮我吗?
i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python
i have tried this:
def get_dblink( dbstring):
"""
Return a database cnx.
"""
global psycopg2
try
cnx = psycopg2.connect( dbstring)
except Exception, e:
print "Unable to connect to DB. Error [%s]" % ( e,)
exit( )
but i get this error: global name 'psycopg2' is not defined
in my main file script.py
i have:
import psycopg2, psycopg2.extras
from misc_defs import *
hostname = '192.168.10.36'
database = 'test'
username = 'test'
password = 'test'
dbstring = "host='%s' dbname='%s' user='%s' password='%s'" % ( hostname, database, username, password)
cnx = get_dblink( dbstring)
can anyone give me a hand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需在第一个代码段中导入 psycopg2 即可。
如果您需要,在第二个片段中“也”导入它是没有问题的(Python 确保模块仅导入一次)。尝试使用全局变量是不好的做法。
所以:在每个模块的顶部,
导入
该特定模块中使用的每个模块。另请注意,
from x import *
(带有通配符)通常不受欢迎:它会使您的命名空间变得混乱,并使您的代码不那么明确。You just need to
import psycopg2
in your first snippet.If you need to there's no problem to 'also' import it in the second snippet (Python makes sure the modules are only imported once). Trying to use
globals
for this is bad practice.So: at the top of every module,
import
every module which is used within that particular module.Also: note that
from x import *
(with wildcards) is generally frowned upon: it clutters your namespace and makes your code less explicit.