[英]Python function to pg_restore a Google Cloud SQL database
[英]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 和/或 PGUSER 設置為適當的值來節省一些輸入。 (有關其他環境變量,請參閱第 30.12 節。)擁有一個 ~/.pgpass 文件也很方便,以避免經常輸入密碼。 有關更多信息,請參閱第 30.13 節。
更多: https : //www.postgresql.org/docs/8.3/app-psql.html
此處討論: 如何以非交互方式為 psql 指定密碼?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.