TypeError:并非在方法参数中的字符串格式化期间转换所有参数

时间:2014-09-24 06:49:51

标签: string formatting psycopg2 python-3.4

对于那些python专家来说,这可能很容易。

import psycopg2
import io
import sys
import pdb
import codecs
import os

def connect_db(db, usr, pw, hst, prt):
    conn = psycopg2.connect(database=db, user=usr, password=pw,
                            host=hst, port=prt)
    return conn

def write_table_to_file(table, connection):
    db_table = io.BytesIO()
    cur = connection.cursor()
    cur.copy_to(codecs.StreamRecoder(db_table, codecs.getencoder('utf-8'),
                                     codecs.getdecoder('latin-1'),
                                     codecs.getreader('utf-8'),
                                     codecs.getwriter('utf-8')), table)
    cur.close()
    return db_table

def write_file_to_table(file_object, table, connection):
    cur = connection.cursor()
    print(table)
    cur.execute("DELETE FROM (%s);",(table))
    file_object.seek(0)  # Set the buffer at position 0 before read
    cur.copy_from(file_object, table)
    cur.close()

def main():
    os.chdir(os.path.abspath('C:/testAJFmidrange'))
    f = open('tctmem70.txt', 'r')
    pw = f.readline().strip()
    con_tctmsv64 = connect_db("x", "y",
                              pw,
                              "z", "5432")
    con_tctmsv64_replica = connect_db("x", "y", "z",
                             "a", "5432")
    try:
        table_name = "a" + sys.argv[1] + "002_ajob"
        print(table_name)
        t = write_table_to_file(table_name, con_tctmsv64)
        pdb.set_trace()
        write_file_to_table(t, "a140729002_ajob", con_tctmsv64_replica)
        con_tctmsv64_replica.commit()
    finally:
        con_tctmsv64.close()
        con_tctmsv64_replica.close()

if __name__ == "__main__":
    sys.exit(main())

错误:

C:\testAJFmidrange>python tctmem70.py 140924
a140924002_ajob
> c:\testajfmidrange\tctmem70.py(48)main()
-> write_file_to_table(t, "a140729002_ajob", con_tctmsv64_replica)
(Pdb) c
a140729002_ajob
Traceback (most recent call last):
  File "tctmem70.py", line 55, in <module>
    sys.exit(main())
  File "tctmem70.py", line 48, in main
    write_file_to_table(t, "a140729002_ajob", con_tctmsv64_replica)
  File "tctmem70.py", line 29, in write_file_to_table
    cur.execute("DELETE FROM (%s);",(table))
TypeError: not all arguments converted during string formatting

尝试了几种不同的喂食方式。检查它是否为字符串类型但似乎没有任何效果。它很奇怪,因为只要我输入字符串文字它就可以正常工作,就在我尝试通过添加它所抱怨的命令行参数来动态计算它。不确定发生了什么事?

1 个答案:

答案 0 :(得分:0)

原来我应该已经阅读了python 3.4的新格式化方法。我用的代码是我在2.7中写的。下面的代码修复了这个问题

def write_file_to_table(file_object, table, connection):
    cur = connection.cursor()
    cur.execute("DELETE FROM {0};".format(table))
    file_object.seek(0)  # Set the buffer at position 0 before read
    cur.copy_from(file_object, table)
    cur.close()