我有一个托管在 Windows 2008 Server RT 虚拟机上的 PostgreSQL 数据库(是的,我知道它应该托管在 Linux 虚拟机上,但这是我的组织规定的。唉......)
我们的 GIS 人员将大量 shapefile 转储到存储库中。我们希望有一个自动进程作为计划任务遍历文件夹。我们希望将这些添加到我们目前正在开发的其他一些流程的 Postgres 地理数据库中
我希望浏览大量的形状文件,并将它们的几何形状和文件名加载到数据库中。
这是我迄今为止所工作的摄取功能的核心部分的要点
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:\temp\temp_shp.bat", "w")
temp_bat.write(r'start /D c:\Program Files (x86)\PostgreSQL\8.4\bin\shp2pgsql.exe' + \
paths + "new_shp_table | psql -d geometry_database")
temp_bat.close()
subprocess.Popen(r"c:\temp\temp_shp.bat")
一旦几何图形被加载到新的数据库表中,我就已经有了代码设置,可以将几何图形从临时表中拉出,并将其加上形状文件名称加载到我们的主数据库表中。我的问题是我可以通过命令提示符执行此操作,但是通过 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)\PostgreSQL\8.4\bin'
# 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)