I'm using a psql command to try and list all the databases in a local postgres instance. Here's the command I'm trying to run:
psql --host localhost --port 55000 --username postgres -At --command 'SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname;' postgres
But when I try using subprocess in a python script to execute the command, I'm running into a problem:
FileNotFoundError: [Errno 2] No such file or directory: 'psql'
Here's my code:
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)
The weird thing is the command works perfectly fine if I try it on my command line outside of python subprocess. I've tried escaping the quotes, I've tried putting it all one one line, but to no avail.
What am I missing here?
CodePudding user response:
psql
is likely not in your python's PATH. Call it by its absolute path instead:
database_select_command = f"""
/usr/bin/psql \
--host {source_host} \
--port {source_port} \
--username {source_user} \
-At --command '{database_select_query}' \
postgres
"""
If you're unsure what the path is, run which psql
to find out.