Python:启动psql查询,不等待响应
我正在使用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 个回答
8
在psycopg2中有一个异步的功能,你不能断开连接,但你可以有效地在后台运行你的任务,并等待结果(如果你想的话)。具体可以查看:
http://initd.org/psycopg/docs/advanced.html
大约在页面中间的位置:
conn = psycopg2.connect(database='mydb', async=1)
如果你在那个连接上运行你的任务,你应该可以让它在没有你程序参与的情况下继续运行。如果你想全面进入异步编程,我建议你看看txpostgres。
http://txpostgres.readthedocs.org/
-g