Search code examples
pythongdal

Multiple line shell commands using Python commands module


I'm trying to write a Python function that transforms a given coordinate system to another using gdal. Problem is that I'm trying to execute the command as one string, but in shell, I have to press enter before entering the coordinates.

x = 1815421
y = 557301

ret = []

tmp = commands.getoutput( 'gdaltransform -s_srs \'+proj=lcc +lat_1=34.03333333333333 
+lat_2=35.46666666666667 +lat_0=33.5 +lon_0=-118 +x_0=2000000 +y_0=500000 +ellps=GRS80 
+units=m +no_defs\' -t_srs epsg:4326 \n' + str(x) + ' ' + str(y) )

I tried it using '\n', but that doesn't work.


Solution

  • My guess is that you run gdaltransform by pressing Enter and the coordinates are read by the program itself from its stdin, not the shell:

    from subprocess import Popen, PIPE
    
    p = Popen(['gdaltransform', '-s_srs', ('+proj=lcc ' 
        '+lat_1=34.03333333333333 ' 
        '+lat_2=35.46666666666667 '
        '+lat_0=33.5 '
        '+lon_0=-118 +x_0=2000000 +y_0=500000 +ellps=GRS80 '
        '+units=m +no_defs'), '-t_srs', 'epsg:4326'],
        stdin=PIPE, stdout=PIPE, universal_newlines=True) # run the program
    output = p.communicate("%s %s\n" % (x, y))[0] # pass coordinates