从 python 呼叫 pg_restore
Call pg_restore from python
我正在尝试自动下载 pg_dump 文件并恢复这些文件。我在执行 pg_restore
命令时遇到问题。我目前正在使用:
from subprocess import PIPE, Popen
import shlex
command = f'pg_restore ' \
f'-h {host} ' \
f'-d {database} ' \
f'-U {username} ' \
f'{file_path}'
command = shlex.split(command)
p = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.communicate(str.encode(f'\r{password}\r'))
然而,这会提示我填写密码(当我填写时,它工作得很好)。
到目前为止我尝试过的:
- 设置
shell = True
(在这种情况下我得到错误[Info] 2019-12-09 14:59:55 - [root] (b'', b'pg_restore: [archiver] input file does not appear to be a valid archive (too short?)\n')
)
- 使用
传递密码
p.stdin.write(f'{self.push_password}\n')
p.stdin.flush()
- 使用
\n
代替 \r
- 仅在
p.communicate
末尾传递 \r
我没主意了,不知道该怎么办。有人知道从 python 调用 pg_restore 时如何自动传递我的密码吗?
两种方式。
设置环境变量:
PGDATABASE, PGHOST, PGPORT and/or PGUSER
在文件中设置
密码可以放在一个文件中,postgresql 会提取它
文档
当默认设置不太正确时,您可以通过将环境变量 PGDATABASE、PGHOST、PGPORT and/or PGUSER 设置为适当的值来节省一些输入。 (对于额外的环境变量,请参阅第 30.12 节。)拥有一个 ~/.pgpass 文件以避免经常输入密码也很方便。有关详细信息,请参阅第 30.13 节。
更多:https://www.postgresql.org/docs/8.3/app-psql.html
此处讨论:How do I specify a password to psql non-interactively?
我正在尝试自动下载 pg_dump 文件并恢复这些文件。我在执行 pg_restore
命令时遇到问题。我目前正在使用:
from subprocess import PIPE, Popen
import shlex
command = f'pg_restore ' \
f'-h {host} ' \
f'-d {database} ' \
f'-U {username} ' \
f'{file_path}'
command = shlex.split(command)
p = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.communicate(str.encode(f'\r{password}\r'))
然而,这会提示我填写密码(当我填写时,它工作得很好)。
到目前为止我尝试过的:
- 设置
shell = True
(在这种情况下我得到错误[Info] 2019-12-09 14:59:55 - [root] (b'', b'pg_restore: [archiver] input file does not appear to be a valid archive (too short?)\n')
) - 使用 传递密码
p.stdin.write(f'{self.push_password}\n')
p.stdin.flush()
- 使用
\n
代替\r
- 仅在
p.communicate
末尾传递
\r
我没主意了,不知道该怎么办。有人知道从 python 调用 pg_restore 时如何自动传递我的密码吗?
两种方式。
设置环境变量:
PGDATABASE, PGHOST, PGPORT and/or PGUSER
在文件中设置
密码可以放在一个文件中,postgresql 会提取它
文档
当默认设置不太正确时,您可以通过将环境变量 PGDATABASE、PGHOST、PGPORT and/or PGUSER 设置为适当的值来节省一些输入。 (对于额外的环境变量,请参阅第 30.12 节。)拥有一个 ~/.pgpass 文件以避免经常输入密码也很方便。有关详细信息,请参阅第 30.13 节。
更多:https://www.postgresql.org/docs/8.3/app-psql.html
此处讨论:How do I specify a password to psql non-interactively?