Python:启动psql查询,不要等待响应

时间:2014-06-26 17:46:32

标签: python postgresql psycopg2

我正在使用python和psycopg2来启动COPY TO CSV,这需要很长时间(可能是几小时)。复制到文件的工作由postgres处理,因此不需要将信息返回到我的python脚本。

我有没有办法将查询传递给postgres,然后在不等待响应的情况下断开连接,以便我的程序可以处理其他任务?

以下是启动作业的方法:

def startJob(self):
    #This bit will take the information and flags from the file and start the psql job
    conn = psycopg2.connect('dbname=mydb user=postgres')
    cur = conn.cursor()
    beginClause = "COPY ("
    selectClause = """SELECT '%s' FROM db """ % ','.join(self.flags)
    whenClause = """WHERE 'start' BETWEEN '%s' AND '%s'""" % self.info['begin'] self.info['end']
    destClause = """) TO '/dest/%s' WITH CSV HEADER""" % self.name

    fullQuery = beginClause + selectClause + whenClause + destClause

    #I want the execute to start the job, and then return so that I can
    #resume regular operation of the program
    cur.execute(fullQuery) 

    conn.close()
    self.changeStatus('progress')

1 个答案:

答案 0 :(得分:4)

psycopg2中存在异步功能,您无法断开连接,但您可以在后台有效地运行您的作业并等待结果(如果您愿意)。参见:

http://initd.org/psycopg/docs/advanced.html

大约一半的时间:

conn = psycopg2.connect(database='mydb', async=1)

如果您在该连接上运行您的工作,您应该可以让它在没有您的程序出勤的情况下运行。如果你想用双脚跳入异步,我建议你看看txpostgres。

http://txpostgres.readthedocs.org/

-g