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')

解决方法:

psycopg2具有异步功能,您无法断开连接,但可以在后台有效地运行作业并等待结果(如果需要).看到:

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

大约一半:

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

如果您在该连接上运行您的工作,则应该可以让它在没有程序参与的情况下运行.如果您想用双脚异步跳,建议您看一下txpostgres.

http://txpostgres.readthedocs.org/

-G

上一篇:python-使用psycopg2将PostgreSQL UUID数组返回为列表


下一篇:共享txpostgres连接池