我正在编写一个脚本,使用 psycopg2 在同一网络上的两台机器之间复制一些数据。我正在替换一些旧的、丑陋的 bash,它用
psql -c -h remote.host "COPY table TO STDOUT" | psql -c "COPY table FROM STDIN"
这看起来既是最简单的也是 most efficient复制的方法。使用 stringIO 或临时文件在 python 中复制很容易,如下所示:
buf = StringIO()
from_curs = from_conn.cursor()
to_curs = to_conn.cursor()
from_curs.copy_expert("COPY table TO STDOUT", buf)
buf.seek(0, os.SEEK_SET)
to_curs.copy_expert("COPY table FROM STDIN", buf)
...但这涉及将所有数据保存到磁盘/内存中。
有没有人想出一种方法来在这样的副本中模仿 Unix 管道的行为?我似乎找不到不涉及 POpen 的 unix-pipe 对象 - 毕竟,也许最好的解决方案是只使用 POpen 和子进程。
最佳答案
您必须将其中一个调用放在单独的线程中。我刚刚意识到你可以使用 os.pipe() ,这使得其余部分变得非常简单:
#!/usr/bin/python
import psycopg2
import os
import threading
fromdb = psycopg2.connect("dbname=from_db")
todb = psycopg2.connect("dbname=to_db")
r_fd, w_fd = os.pipe()
def copy_from():
cur = todb.cursor()
cur.copy_from(os.fdopen(r_fd), 'table')
cur.close()
todb.commit()
to_thread = threading.Thread(target=copy_from)
to_thread.start()
cur = fromdb.cursor()
write_f = os.fdopen(w_fd, 'w')
cur.copy_to(write_f, 'table')
write_f.close() # or deadlock...
to_thread.join()
关于python - 使用 psycopg2 在 python 中管道 postgres COPY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6765310/