Home>

essence: You need to work a script over the POSTGRES output after executing the \ DRS command. Through the PSQL command is performed, the output is normal. But when I want to repeat the same through Psycopg2, it does not work:

input:

Cursor.Execute ('\ DRS')

Output:

psycopg2.errors.syntaxerror: Syntax Error at or Near "\"

p.s. R "\ DRS", also does not work ...

Looked about the team in postgrespro.ru/docs/postgrespro/10/app-psql Isn't it in interactive communication with the base? In Execute you need to pass a SQL query, and the team in your question is different

gil9red2021-08-11 05:51:32

Well, how then to execute this command using PSYCOPG2?

Артур Гильметдинов2021-08-11 05:58:04
  • Answer # 1

    If you need from the script to execute an interactive command, you will need to run the program for the base ( PSQL ) and introduce a command to it \ DRS. , after counting the result

    An example is taken from an answer with Enso:

    Import Sys
    Import subprocess
    Import psycopg2.
    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))
    

    Result:

    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)
    
  • Answer # 2

    If you need from the script to execute an interactive command, you will need to run the program for the base ( PSQL ) and introduce a command to it \ DRS. , after counting the result

    An example is taken from an answer with Enso:

    Import Sys
    Import subprocess
    Import psycopg2.
    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))
    

    Result:

    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)