Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute non sql commands in psycopg2

How can execute non sql commands like

\connect
\dl
\dt
\du
\d+ table_name 

...etc

in psycopg2 ??

cur.execute("\dl")

when try to do it with cursor , I get error

syntax error at or near "\"
LINE 1: \dl
like image 638
LightSith Avatar asked Dec 05 '25 22:12

LightSith


2 Answers

These non-sql commands are specific for the psql - PostgreSQL interactive terminal. You cannot execute them with psycopg2, but you can run psql from your app. The below complete example in Python 3.6 uses subprocess:

import psycopg2
import sys
import subprocess

conn = psycopg2.connect(host='localhost', dbname='test', user='postgres')
conn.autocommit = True

cur = conn.cursor()
cur.execute('create table my_table(id int primary key, str text)')

res = subprocess.run('psql -c "\d+ my_table" test postgres', stdout=subprocess.PIPE)
print(res.stdout.decode(sys.stdout.encoding))

Output:

                                  Table "public.my_table"
 Column |  Type   | Collation | Nullable | Default | Storage  | Stats target | Description 
--------+---------+-----------+----------+---------+----------+--------------+-------------
 id     | integer |           | not null |         | plain    |              | 
 str    | text    |           |          |         | extended |              | 
Indexes:
    "my_table_pkey" PRIMARY KEY, btree (id)
like image 156
klin Avatar answered Dec 08 '25 12:12

klin


Those commands are implemented by the psql command-line tool, not by the PostgreSQL server. Some of them (like \dt) have SQL equivalents (like SELECT … FROM INFORMATION_SCHEMA.tables -- details here), but others (like \connect) do not. If you want to connect to another Postgres server, create a new connection object.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!