我正在编写一个脚本,使用 psycopg2 在同一网络上的两台机器之间复制一些数据。我正在替换一些旧的、丑陋的 bash 来进行复制
psql -c -h remote.host "COPY table TO STDOUT" | psql -c "COPY table FROM STDIN"
这看起来既是最简单的又是最有效率的 http://www.depesz.com/index.php/2007/07/05/how-to-insert-data-to-database-as-fast-as-possible/方式进行复制。使用 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() http://docs.python.org/release/2.6/library/os.html#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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)