在不存在的情况下创建表;否则重新填充

2024-04-26 13:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在python脚本中,一个表被删除并重新创建,但是我注意到如果表不存在,它就会出错。在

shp2pgsql = r"shp2pgsql -s 4135 -d "+path+" asmithe.bigtable "
psql = 'psql -U asmithe -h example.org -d xyz -c "ANALYZE asmithe.bigtable"' 
subprocess.Popen(shp2pgsql +" | "+psql, shell=True).wait()

给予

^{pr2}$

如何保护它,以便如果表不存在,它只会创建它?在


Tags: pathorg脚本trueexampleshellanalyzesubprocess
2条回答

正如在另一个答案中所说,-c选项导致psql无法读取管道。 为什么要执行分析?在这个地方是错误的。只需将其移除:

shp2pgsql = r"shp2pgsql -s 4135 -d "+path+" asmithe.bigtable "
psql = 'psql -U asmithe -h example.org -d xyz' 
subprocess.Popen(shp2pgsql +" | "+psql, shell=True).wait()

-c标志将psql指向使用-c后面的字符串作为命令。 演示:

#!/bin/sh

    # This one fails; the pipe is never read
echo 'create TABLE omg (wtf integer NOT NULL);' \
     | psql -U postgres -d postgres -c 'ANALYZE public.omg;'

    # this one works; *only* the pipe (stdin) is read and executed
echo 'CREATE TABLE omg (wtf integer NOT NULL); ANALYZE public.omg; DROP TABLE public.omg;' \
     | psql -U postgres -d postgres

相关问题 更多 >