Search code examples
pythonpostgresqlsubprocesspopenraster

How to use subprocess Popen?


I'm trying to execute a command using Popen.

The command uses some PostGIS/Postgresql utility programs to upload a raster file to a database and works when executed from the command line. It uses unix style pipes to chain 2 commands and looks like this:

"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe" -d -I -C -e -Y -F -t 128x128 "C:\\temp\\SampleDTM\\SampleDTM.tif" test | "C:\\Program Files\\PostgreSQL\\9.2\\bin\\psql.exe" -h localhost -p 5432 -d adr_hazard -U postgres

When using within Python, I make it a string with the ' codes:

command = '"C:\\Program Files\\PostgreSQL\\9.2\\bin\\raster2pgsql.exe" -d -I -C -e -Y -F -t 128x128 "C:\\temp\\SampleDTM\\SampleDTM.tif" test | "C:\\Program Files\\PostgreSQL\\9.2\\bin\\psql.exe" -h localhost -p 5432 -d adr_hazard -U postgres'

attempting to execute it results in an error:

p = subprocess.Popen(command)

ERROR: Unable to read raster file: test

The error seems like the command was not parsed correctly (it is interpreting the wrong argument as the raster file)

Am I using Popen wrong?


Solution

  • Your command uses pipe |. It requires a shell:

    p = subprocess.Popen(command, shell=True)
    

    The command itself as far as I can tell looks ok.