使用 psycopg2 在 python 上进行多进程
Multiprocess over python with psycopg2
我正在 python 将许多记录添加到 Postgres 数据库中,因为我必须插入数百万条记录我需要并行化 2 个函数:
insert_A(cur)
insert_B(cur)
其中:
conn=psycopg2.connect(.....)
cur = conn.cursor()
我尝试了在另一个 post 中找到的解决方案,在堆栈溢出中,如:
result1= pool.apply_async(insert_A, cur)
result2= pool.apply_async(insert_B, cur)
answer1=result1.get(timeout=15)
answer2=result2.get(timeout=15)
但是我得到了这个错误:
追溯(最近一次通话最后一次):
文件 "test.py",第 387 行,在
中
answer1=result1.get(超时=15)
文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py”,第 558 行,在 get
中
提高 self._value
psycopg2.InterfaceError:游标没有连接
有人可以帮助我吗? :(
据this issue报告,在 psycopg2 上不可能在单独的进程上使用连接,必须在工作进程中建立连接。
最后我是这样解决的:
if __name__ == '__main__':
p = Process(target=insert_A, args=(ARG,))
q = Process(target=insert_measurement_real, args=(ARG,))
p.start()
q.start()
p.join()
q.join()
并在函数内部创建连接而不是在函数外部创建连接(并将连接作为参数传递)...
我正在 python 将许多记录添加到 Postgres 数据库中,因为我必须插入数百万条记录我需要并行化 2 个函数:
insert_A(cur)
insert_B(cur)
其中:
conn=psycopg2.connect(.....)
cur = conn.cursor()
我尝试了在另一个 post 中找到的解决方案,在堆栈溢出中,如:
result1= pool.apply_async(insert_A, cur)
result2= pool.apply_async(insert_B, cur)
answer1=result1.get(timeout=15)
answer2=result2.get(timeout=15)
但是我得到了这个错误:
追溯(最近一次通话最后一次):
文件 "test.py",第 387 行,在
中
answer1=result1.get(超时=15)
文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py”,第 558 行,在 get
中
提高 self._value
psycopg2.InterfaceError:游标没有连接
有人可以帮助我吗? :(
据this issue报告,在 psycopg2 上不可能在单独的进程上使用连接,必须在工作进程中建立连接。
最后我是这样解决的:
if __name__ == '__main__':
p = Process(target=insert_A, args=(ARG,))
q = Process(target=insert_measurement_real, args=(ARG,))
p.start()
q.start()
p.join()
q.join()
并在函数内部创建连接而不是在函数外部创建连接(并将连接作为参数传递)...