简体   繁体   English

如何使用 PYTHON 进行 PSQL 复制

[英]How to PSQL COPY with PYTHON

Trying to run a PSQL COPY command using python.尝试使用 python 运行 PSQL COPY 命令。 I'm able to connect to the right DB in the given kube cluster.我能够连接到给定 kube 集群中的正确数据库。

The lose track of the shell once im on postgres.一旦我在 postgres 上,shell 就失去了踪迹。 When i exit, i get the following error.当我退出时,我收到以下错误。 Is there any wrong with the quotes that I'm using in the PSQL command in the os.system call.我在 os.system 调用的 PSQL 命令中使用的引号有什么问题吗?

import os
import subprocess

conn = 'gcloud container clusters get-credentials clusterA --zone us-west --project projectX'
pg = 'kubectl -n DB exec -it postgres -- bash'


if __name__ == '__main__':

   subprocess.call(back_clus_conn, shell=True)
   subprocess.call(pg, shell=True)
   os.system('psql -U postgres -c "\COPY (SELECT * FROM "public"."tableName") TO tableName.csv DELIMITER ',' CSV"')

ERROR:错误:

 kubeconfig entry generated for clusterA.
 Defaulted container "postgres" out of: postgres, postgres-exporter
 bash-5.0#
 bash-5.0# exit
 exit
 Traceback (most recent call last):
 File "test.py", line 19, in <module>
 os.system('psql -U postgres -c "\COPY (SELECT * FROM "public"."tableName") TO tableName.csv DELIMITER ',' CSV"')
 TypeError: system() takes exactly 1 argument (2 given)

You can just run the command in the postgres container exec subprocess call, something like this:您可以在 postgres 容器 exec 子进程调用中运行命令,如下所示:

import subprocess

conn = 'gcloud container clusters get-credentials clusterA --zone us-west --project projectX'
copy_cmd = 'psql -U postgres -c "\COPY (SELECT * FROM "public"."tableName") TO tableName.csv DELIMITER ',' CSV"'
pg = f'kubectl -n DB exec -it postgres -- bash -c {copy_cmd}'

if __name__ == '__main__':
   subprocess.call(back_clus_conn, shell=True)
   subprocess.call(pg, shell=True)



Based on sticky bit , It tells you to give it two arguments instead of one.根据sticky bit ,它告诉你给它两个arguments而不是一个。

Currently your code is:目前您的代码是:

 os.system('psql -U postgres -c "\COPY (SELECT * FROM "public"."tableName") TO tableName.csv DELIMITER ',' CSV"')

You may try to Add \',\' to be recognizable by Phyton您可以尝试添加\',\'以被 Phyton 识别

os.system('psql -U postgres -c "\COPY (SELECT * FROM "public"."tableName") TO tableName.csv DELIMITER \',\' CSV"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM