读取多个变量Python

时间:2017-05-01 19:49:43

标签: python postgresql

我有一个函数我试图用4个不同的变量执行哪些调用:

def listdbtables(dbname, user, host, password):
    try:
        conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % dbname, % user, % host, % password)
        curs = conn.cursor()
        b = curs.execute("\l")
        print b
    except psycopg2.DatabaseError, ex:
        print "I am unable to connect the database: " + ex
        sys.exit(1)

我无法使用当前设置读取变量,如何在conn变量中正确调用变量。

编辑:这是我看到的错误:

      File "./pg_meta.py", line 35
    conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" (% dbname, % user, % host, % password))
                                                                             ^
SyntaxError: invalid syntax

3 个答案:

答案 0 :(得分:2)

试试这个:

def listdbtables(dbname, user, host, password):
    try:
        conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % (dbname, user, host,password,))
        curs = conn.cursor()
        b = curs.execute("\l")
        print b
    except psycopg2.DatabaseError, ex:
        print "I am unable to connect the database: " + ex
        sys.exit(1)

格式部分需要是多个值的元组。您还应该考虑使用String.format

答案 1 :(得分:1)

我认为这是错误的语法:

conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % dbname, % user, % host, % password)

将其更改为:

conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" %(dbname, user, host, password))

使用.format()的另一种方式:

conn = psycopg2.connect("dbname = {0} username = {1} host = {2} pass = {3}".format(dbname, user, host, password))

答案 2 :(得分:1)

您的错误是说您的程序语法不正确。将%运算符与多个变量一起使用时,Python要求您使用括号。请将您的代码更改为:

conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % (dbname, % user, % host, % password))

但是,在较新的Python版本中将变量格式化为字符串的推荐方法是使用.format()方法,而不是使用%的旧样式字符串格式:

conn = psycopg2.connect("dbname = {} username = {} host = {} pass = {}".format(
    dbname,  user, host,  password)
)

这两种方法都有其优点和缺点,所以我鼓励您找到最适合您的方法。比较这两种方法的好网站是pyformat.info