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

vas*_*man 4 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')
Run Code Online (Sandbox Code Playgroud)

Gre*_*reg 6

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

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

大约一半:

conn = psycopg2.connect(database='mydb', async=1)
Run Code Online (Sandbox Code Playgroud)

如果您在该连接上运行您的作业,您应该能够让它在没有您的程序参与的情况下运行。如果您想双脚异步跳转,我建议您查看 txpostgres。

http://txpostgres.readthedocs.org/

-G

  • 这非常好,并且适用于我正在做的事情。然而,这似乎限制了我每个数据库连接的一个事务(现在很好,但考虑增长)。我是否需要使用更多的数据库连接来运行同时查询?我应该使用子流程吗? (2认同)