Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading