Python – How do I get a list of databases in PostgreSQL in python

How do I get a list of databases in PostgreSQL in python… here is a solution to the problem.

How do I get a list of databases in PostgreSQL in python

I want to get a list of all databases in a Postgresql server in a python list.
Basically then I want to create those in another database
But I can’t get it.

Here’s what I tried

config_read = {
          'host':'psql-002',
          'database':'tesdb',
          'user':'pguser',
          'port':'5432',
          'password':'mypass'
          }

class ExportPSQL():

def __init__(self):
        try:
            conn = psycopg2.connect(**config_read) 
            self.conn = conn
        except:
            print "Eror Connecting database"  

def run(self):
    # Get a list of databases with :
        db_command=" psql -h localhost -U pguser tesdb -c '\l'"
        db_list = os.popen(db_command)

Solution

Use >pg_dumpall >psql as a super user

pg_dumpall -h localhost -U postgres -f pg_dumpall.sql

If you only want to copy the schema, use the --schema-only parameter.

Restore it to another cluster

psql -f pg_dumpall.sql postgres

Related Problems and Solutions