psycopg2转义字符问题

psycopg2 escape character issue

我正在尝试编写 python 脚本以定期使用 \COPY TO 将 select 语句导出到 CSV 文件。

查询是

postgres=# \copy (select * from mytable where temp>32.5) to ...

此命令适用于 psql 命令行。 但是在我的脚本中它给出了这个错误,大概与字符串中的转义字符有关:

psycopg2.ProgrammingError: syntax error at or near "\"
LINE 2:         \copy (select * 
                ^

我已经在我的 python 代码中尝试了明显的“//”但无济于事。似乎转义正斜杠或不转义正斜杠会产生相同的错误。

\copy 只是一个 psql 命令。使用 Psycopg 的 copy_expert cursor method:

cursor.copy_expert (
    'copy (select * from mytable where temp>32.5) to stdout'
    '\path\to\file.csv'
),