![](/img/trans.png)
[英]What wrong am I doing in the below code? When I run this program I am getting error
[英]I'm getting "No such file or directory: 'psql'" when I try to run a psql command with Python subprocess. What am I doing wrong?
我正在使用 psql 命令嘗試列出本地 postgres 實例中的所有數據庫。 這是我要運行的命令:
psql --host localhost --port 55000 --username postgres -At --command 'SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname;' postgres
但是當我嘗試在 python 腳本中使用子進程來執行命令時,我遇到了一個問題:
FileNotFoundError: [Errno 2] No such file or directory: 'psql'
這是我的代碼:
import subprocess
import shlex
source_host = "localhost"
source_port = "55000"
source_user = "postgres"
source_password = "postgrespw"
database_select_query = "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname;"
database_select_command = f"""
psql \
--host {source_host} \
--port {source_port} \
--username {source_user} \
-At --command '{database_select_query}' \
postgres
"""
print(database_select_command)
print(shlex.split(database_select_command))
output = subprocess.run(
shlex.split(database_select_command),
capture_output=True,
shell=False,
env={"PGPASSWORD": source_password},
)
print(output)
奇怪的是,如果我在 python 子進程之外的命令行上嘗試該命令,則該命令可以正常工作。 我試過 escaping 引號,我試過把它全部放在一行,但無濟於事。
我在這里想念什么?
psql
可能不在您的python 路徑中。 而是通過其絕對路徑調用它:
database_select_command = f"""
/usr/bin/psql \
--host {source_host} \
--port {source_port} \
--username {source_user} \
-At --command '{database_select_query}' \
postgres
"""
如果您不確定路徑是什么,請運行which psql
來查找。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.