Python脚本将ShapeFile摄入使用Windows上的SHP2PGSQL.EXE的PostgreSQL/Post



我在Windows 2008服务器RT虚拟机上托管了一个PostgreSQL数据库(是的,我知道它应该托管在Linux VM上...)

我们的GIS家伙将大量的Shapefiles倾倒到存储库中。我们想拥有一个自动进口,该自动进度作为计划的任务浏览文件夹。我们想将它们添加到我们当前正在开发的其他过程

的其他过程中,将它们添加到我们的Postgres Geodatabase中

我希望浏览大量的shapefiles,并将其几何形状和文件名加载到数据库中。

这是我到目前为止工作的摄入功能的核心部分的要点

import os, subprocess
base_dir = r"c:shape_file_repository"
full_dir = os.walk(base_dir)
shapefile_list = []
for source, dirs, files in full_dir:
    for file_ in files:
        if file_[-3:] == 'shp':
            #print "Found Shapefile"
            shapefile_path = base_dir + '/' + file_
            shapefile_list.append(shapefile_path)
for paths in shapefile_list:  
    #This is the part where I keep running into trouble. os.system also didnt work
    temp_bat = open(r"c:temptemp_shp.bat", "w")
    temp_bat.write(r'start /D c:Program Files (x86)PostgreSQL8.4binshp2pgsql.exe' + 
                   paths + "new_shp_table | psql -d geometry_database")
    temp_bat.close()
    subprocess.Popen(r"c:temptemp_shp.bat")

一旦将几何形状加载到新的数据库表中,我已经有代码设置,可以将几何形状从临时表中拉出并加载该代码,并加载ShapeFile名称加入我们的主数据库表。我的问题是我可以通过命令提示进行此操作,但是通过Python运行Windows命令或将它们输出到批处理文件,然后运行它们似乎根本无法正常工作。

这是一些应该使事情起作用的修改。请注意,如果需要通知任何命令,则需要进一步修改。请注意,它将失败多个shapefile,因为new_shp_table表将已经存在,直到您有进一步的逻辑将该表移动或重命名为其他位置,或加载它。

另外,请注意,PostgreSQL 8.4将于今年晚些时候到达寿命,因此您可能需要计划在为时已晚之前升级到最近的版本。

import os, subprocess
# Choose your PostgreSQL version here
os.environ['PATH'] += r';C:Program Files (x86)PostgreSQL8.4bin'
# http://www.postgresql.org/docs/current/static/libpq-envars.html
os.environ['PGHOST'] = 'localhost'
os.environ['PGPORT'] = '5432'
os.environ['PGUSER'] = 'someuser'
os.environ['PGPASSWORD'] = 'clever password'
os.environ['PGDATABASE'] = 'geometry_database'
base_dir = r"c:shape_file_repository"
full_dir = os.walk(base_dir)
shapefile_list = []
for source, dirs, files in full_dir:
    for file_ in files:
        if file_[-3:] == 'shp':
            shapefile_path = os.path.join(base_dir, file_)
            shapefile_list.append(shapefile_path)
for shape_path in shapefile_list:
    cmds = 'shp2pgsql "' + shape_path + '" new_shp_table | psql '
    subprocess.call(cmds, shell=True)

最新更新