python,访问psycopg2形成一个def?

i-M*_*nus 2 python 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( )
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:未定义全局名称'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)
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我一把吗?

Chr*_*heD 5

你只需要import psycopg2在你的第一个片段中.

如果你需要在第二个片段中"导入"它没有问题(Python确保模块只导入一次).试图使用globals这是不好的做法.

因此:在每个模块的顶部,import在该特定模块中使用的每个模块.

另外:请注意from x import *(使用通配符)通常不赞成:它使您的命名空间变得混乱并使您的代码不那么明确.