簡體   English   中英

從 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'))

然而,這提示我填寫我的密碼(當我填寫時,它工作得很好)。

到目前為止我嘗試過的:

  • set 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM