I am unable to call shp2pgsql using python as I have to pass various options like (-s -a -i) and I am not getting the required output ..

Method I am using is

p1 = subprocess.Popen(["cmd", "/C", "shp2pgsql","-a","-s 4326","roads.shp" "roads", ">","roads.sql"],stdout=subprocess.PIPE)


as my intension is to add the features of the shapefile into the already existing table in the database

I am done with the environment settings.. roads.shp is the name of the shapefile roads is the table name and roads.sql is the sql file name..


I suggest you can use the following codes:

p1 = subprocess.Popen(["cmd", "/C", "shp2pgsql","-a","-s 4326","roads.shp", "roads"], stdout=subprocess.PIPE)
stdout, stderr = p1.communicate()
with open('roads.sql', 'w') as f:

Another alternative method (if you want to import this into postgresql database):

p1 = subprocess.Popen(["cmd", "/C", "shp2pgsql","-a","-s 4326","roads.shp", "roads"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen(['psql',  '-d db'], stdin=p1.stdout, 
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr= p2.communicate()


  1. http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate
  2. http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

This seems a bit convoluted. Why not use os.system instead? Just write out / manipulate the command as a string and feed it to os.system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.