【发布时间】:2017-09-08 20:50:00
【问题描述】:
问题:在 Python 脚本中使用 PSQL pg_dump 和 pg_restore 并使用 subprocess 模块。
背景:我正在使用来自本地主机的以下python 2.7 脚本(即Ubuntu 14.04.5 LTS)在PSQL 服务器(即PostgreSQL 9.4.11)中创建表的备份并恢复它在较新版本的 PSQL 服务器(即PostgreSQL 9.6.2)中进入远程主机(即Ubuntu 16.04.2 LTS)。
#!/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”失败:致命:用户密码验证失败 "username"\nFATAL: 用户密码验证失败 "用户名"\n')*
我已经通过在 shell 中执行 pg_restore 的命令检查了凭据和输出,并且我还包含了 .pgpass 的凭据(尽管不相关,因为我在 p.communicate() 中传递了密码)
有人有类似经历吗?我几乎被困住了!
问候, D.
【问题讨论】:
标签: python subprocess psql pg-dump pg-restore