我有一个数据库,我想用我的 python 代码备份它。
我试图将我的代码基于 this discussion 中的代码使用子进程模块和 pg_dump
。我现在的问题是我必须手动输入密码才能获取备份文件。我在某处读到过执行 .pgpass
但我确实想看看是否可以在 subprocess 模块中执行此操作。
我的代码如下:
from subprocess import Popen, PIPE
from pathlib import Path, PureWindowsPath
def backup():
version = 11
postgresDir = Path("C:/Program Files/PostgreSQL/{}/bin/".format(version))
directory = PureWindowsPath(postgresDir)
filename = 'myBackUp2' # output filename here
saveDir = Path("D:/Desktop/{}.tar".format(filename)) # output directory here
file = PureWindowsPath(saveDir)
host = 'localhost'
user = 'postgres'
port = '5434'
dbname = 'database_name' # database name here
proc = Popen(['pg_dump', '-h', host, '-U', user, '-W', '-p', port,
'-F', 't', '-f', str(file), '-d', dbname],
cwd=directory, shell=True, stdin=PIPE)
proc.wait()
backup()
上面的代码有效,我输入密码就创建了备份。我尝试用下面的代码替换 proc.wait()
以消除手动输入密码的需要:
return proc.communicate('{}\n'.format(database_password))
但是我会收到这个错误:
TypeError: a bytes-like object is required, not 'str'
这可以在子流程中完成吗?如果是,怎么办?
最佳答案
On Microsoft Windows the file is named
%APPDATA%\postgresql\pgpass.conf
(where%APPDATA%
refers to the Application Data subdirectory in the user's profile).
和-w
或--no-password
command line option (而不是 -W
)
-w
--no-password
Never issue a password prompt. If the server requires password authentication and a password is not available by other means such as a .pgpass file, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.
关于Python 子进程模块 |带密码的 Postgres pg_dump,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54490805/