Search code examples
pythonpostgresqlsubprocess

How to print the RAISE NOTICE output , if I am using subprocess along with psql?


I'm using postgres 16 remotely. The query loops to do a batch update and shows the loading percentage of the entire table with:

RAISE NOTICE 'Completion percentage: %', percentage_complete;

How do I display it in the cli where my python script that uses subprocess to start psql started?

I tried this:

process = subprocess.Popen(query_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env={"PGPASSWORD": db_pass})

        # Leggi l'output in tempo reale
        while True:
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                print(output.strip())

and this:

subprocess.run(query_command, shell=True, text=True, capture_output=True, env={"PGPASSWORD": db_pass})

But didnt give me nothing.


Solution

  • The RAISE NOTICE messages are sent to the stderr stream, not stdout. Read from stderr isntead of stdout to get the messages:

    process = subprocess.Popen(query_command, shell=True, stdout=subprocess.PIPE, text=True, env={"PGPASSWORD": db_pass})
    while True:
        output = process.stderr.readline()
        if output == '' and process.poll() is not None:
            break
        if output:
            print(output.strip())