问题:在Python脚本中使用PSQL的pg_dump
和pg_restore
命令,并使用subprocess
模块。
背景:我正在使用以下来自本地主机(即Ubuntu 14.04.5 LTS
)的python 2.7
脚本,创建一个PSQL服务器(即PostgreSQL 9.4.11
)表的备份,并将其恢复到远程主机(即Ubuntu 16.04.2 LTS
)上的新版本PSQL服务器(即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()
函数返回以下错误信息:
我已经通过在shell中执行('', 'Password: \npg_restore: [archiver (db)]连接到数据库“database_name”失败:FATAL:用户“username”的密码身份验证失败\nFATAL:用户“username”的密码身份验证失败\n')*
pg_restore
命令来检查凭据和输出,并且我还包含了凭据到.pgpass(虽然不相关,因为我正在p.communicate()
中传递密码)。有人有类似的经历吗?我真的卡住了!
问候, D.
subprocess.run(...)
时,我遇到了困难,无法使用input=
关键字。没有使用shell=True
关键字,但是使用了env=
就解决了问题。这可能与某些奇怪的_tty_相关问题有关。 - Dimitri Hautot