从 python 执行受密码保护的 psql

Executing password-protected psql from python

我需要在 Windows 上从 Python 执行以下命令:

psql -h localhost -p 5432 -U postgres -f script.sql db_name

当 git bash / powershell 运行 时,上面的脚本工作正常。在终端中输入脚本后,我需要提供一个密码来确认它(类似于使用 sudo 时)。

我该怎么做?我一直在寻找我认为基于 linux 的解决方案。

如何在 Windows 上执行此操作?我尝试了很多涉及 subprocess 的解决方案变体,即:

import subprocess

p2 = subprocess.Popen(
    'psql -h localhost -p 5432 -U postgres -f script.sql db_name',
    stdin=subprocess.PIPE,
    stderr=subprocess.PIPE,
    universal_newlines=True)

print('this will print')
sudo_prompt = p2.communicate('THE_PASSWORD' + '\n')[1]
print('this will not')

比调用 psql 并明确提及您的密码更好的选择(更安全)是拥有一个 .pgpass file as described in the docs 文件(并对其进行保护,例如 chmod 600 ~/.pgpass)。这会将您的密码排除在 运行 个进程列表之外。

在 Windows:

On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).