I am trying to convert MapINFO tabs to ESRI Shapefiles using FW Tools. I downloaded the tools and can run the FW Tools Shell and convert no problem:
ogr2ogr -f "ESRI Shapefile" E:\CABWorking\MapINFO2SHP\SHP\LincsBoundary.shp E:\CABWorking\MapINFO2SHP\MapINFOData\Lincolnshire.tab
In the shell you can type python and use the shell as a python interpreter. Awesome, but I need this to work as I want to convert a ton of MapINFO files at once.
My problem is: I can't figure out how to get the following code to work in a python environment. I've been searching all morning and just have no clue. Any help would be awesome!
Thanks!
Answer
In Python the os module provides a quick and dirty way to run a command line argument such as the one you posted as part of a larger script as outlined in the Python documentation
import os
command = "ogr2ogr -f \"ESRI Shapefile\" E:\\CABWorking\\MapINFO2SHP\\SHP\\LincsBoundary.shp E:\\CABWorking\\MapINFO2SHP\\MapINFOData\\Lincolnshire.tab"
os.system(command)
Note the use of backslashes to escape characters such as " and \ in the command string.
As I said, this is quick and dirty, the Pythonic way to do this is to use the Subprocess library which provides the same functionality but in a more stable framework, and with some more features:
import os
command = "ogr2ogr -f \"ESRI Shapefile\" E:\\CABWorking\\MapINFO2SHP\\SHP\\LincsBoundary.shp E:\\CABWorking\\MapINFO2SHP\\MapINFOData\\Lincolnshire.tab"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000)
#the third command suppresses the opening of a new window for each process
#and can be removed if this is not the desired outcome
process.wait() #waits for one process to complete before launching another one
I used this answer to solve my issue. Thanks a ton @sgrieve. The final code ended up being:
import os, glob
inputDir = raw_input("==> ") # Had to have this code compatible with 2.3.4
outputDir = raw_input("==> ") # So that meant no easy file dialog boxes
TabFiles = glob.glob(str(inputDir) + '/*.tab')
for TabFile in TabFiles:
TabFileName = TabFile[(TabFile.rfind("\\"))+1:(TabFile.rfind("."))]
command = 'ogr2ogr -f "ESRI Shapefile" ' + outputDir + "/" + TabFileName + '.shp ' + TabFile
os.system(command)
I'd then open the FWTools Shell, enter python and call the script with:
execfile("script")
No comments:
Post a Comment