开发者

python, accessing a psycopg2 form a def?

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开发者_StackOverflow='%s'" % ( hostname, database, username, password)

cnx = get_dblink( dbstring)

can anyone give me a hand?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜