【发布时间】:2020-12-07 19:09:45
【问题描述】:
我需要在 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')
【问题讨论】:
-
只需在子进程调用前设置环境变量
PGPASSWORD -
这似乎不起作用,即使我在执行 psql 从终端本身之前执行
set PGPASSWORD=THE_PASSWORD。