问题:使用 PSQLpg_dump
并pg_restore
在 Python 脚本中使用subprocess
模块。
背景:我正在使用python 2.7
来自 localhost (ie) 的以下脚本Ubuntu 14.04.5 LTS
在 PSQL 服务器 (ie) 中创建表的备份,PostgreSQL 9.4.11
并将其恢复到Ubuntu 16.04.2 LTS
新版本的 PSQL 服务器 (ie) 中的远程主机 (ie PostgreSQL 9.6.2
)。
#!/usr/bin/python
from subprocess import PIPE,Popen
def dump_table(host_name,database_name,user_name,database_password,table_name):
command = 'pg_dump -h {0} -d {1} -U {2} -p 5432 -t public.{3} -Fc -f /tmp/table.dmp'\
.format(host_name,database_name,user_name,table_name)
p = Popen(command,shell=True,stdin=PIPE)
return p.communicate('{}\n'.format(database_password))
def restore_table(host_name,database_name,user_name,database_password):
command = 'pg_restore -h {0} -d {1} -U {2} < /tmp/table.dmp'\
.format(host_name,database_name,user_name)
p = Popen(command,shell=True,stdin=PIPE)
return p.communicate('{}\n'.format(database_password))
def main():
dump_table('localhost','testdb','user_name','passwd','test_tbl')
restore_table('remotehost','new_db','user_name','passwd')
if __name__ == "__main__":
main()
当我按上述顺序使用函数时,dump_table()
函数成功完成并创建/tmp/table.sql
文件,但restore_table()
函数返回以下错误:
('', '密码:\npg_restore: [archiver (db)] 连接到数据库“database_name”失败:致命:用户“用户名”的密码验证失败\n致命:用户“用户名”的密码验证失败\n')*
我已经通过在 shell 中执行命令检查了凭据和输出,pg_restore
并且我还包含了 .pgpass 的凭据(尽管不相关,因为我正在传递密码p.communicate()
)
有人有类似的经历吗?我几乎被困住了!
问候,D。