Python 子进程模块 |带密码的 Postgres pg_dump

标签 python python-3.x postgresql subprocess pg-dump

我有一个数据库,我想用我的 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'

这可以在子流程中完成吗?如果是,怎么办?

最佳答案

使用a password file.

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/

相关文章:

python - 是否有标准的文档字符串格式来显示采用函数的参数所需的签名?

python - Python 中的纯虚方法

python - 声明字典时如何保留键的顺序

python - 读取不同网页的内容,然后将其添加到另一个URL中

python - 如何在Python中将所有引用变量设置为None?

file - 如何在 Python 3 中找到 "current"源文件?

.net - Nhibernate cfg xml 无法连接到 Postgres

python - 使用列表索引多索引数据帧

PostgreSQL UUID 类型性能

postgresql - SSRS 和 PostgreSQL : How do I pass an optional parameter?