使用Python命令模块的多行shell命令
我正在尝试编写一个Python函数,它使用gdal将给定的坐标系转换为另一个坐标系。问题是我试图将命令作为一个字符串执行,但在shell中,我必须在输入坐标之前按enter键使用Python命令模块的多行shell命令,python,gdal,Python,Gdal,我正在尝试编写一个Python函数,它使用gdal将给定的坐标系转换为另一个坐标系。问题是我试图将命令作为一个字符串执行,但在shell中,我必须在输入坐标之前按enter键 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_
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) )
我用“\n”试过了,但不起作用
from subprocess import *
c = 'command 1 && command 2 && command 3'
# for instance: c = 'dir && cd C:\\ && dir'
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
print handle.stdout.read()
handle.flush()
如果我没有弄错的话,这些命令将在一个“会话”上执行,从而在命令之间保留您需要的任何信息格式
更准确地说,使用shell=True
(根据我所了解的)是,如果给定一个命令字符串而不是一个列表,则应该使用它。如果您想使用列表,建议如下:
import shlex
c = shlex.split("program -w ith -a 'quoted argument'")
handle = Popen(c, stdout=PIPE, stderr=PIPE, stdin=PIPE)
print handle.stdout.read()
然后捕获输出,或者您可以使用开放流并使用handle.stdin.write()
,但这有点棘手
除非您只想执行、读取和死亡,.communicate()
是完美的,或者只是。检查输出()
可以在此处找到有关Popen如何工作的好信息(尽管主题不同):
解决方案 无论如何,这应该是可行的(您必须重定向STDIN和STDOUT): 如果我没有弄错的话,这些命令将在一个“会话”上执行,从而在命令之间保留您需要的任何信息格式 更准确地说,使用
shell=True
(根据我所了解的)是,如果给定一个命令字符串而不是一个列表,则应该使用它。如果您想使用列表,建议如下:
import shlex
c = shlex.split("program -w ith -a 'quoted argument'")
handle = Popen(c, stdout=PIPE, stderr=PIPE, stdin=PIPE)
print handle.stdout.read()
然后捕获输出,或者您可以使用开放流并使用handle.stdin.write()
,但这有点棘手
除非您只想执行、读取和死亡,.communicate()
是完美的,或者只是。检查输出()
可以在此处找到有关Popen如何工作的好信息(尽管主题不同):
解决方案 无论如何,这应该是可行的(您必须重定向STDIN和STDOUT):
我猜您可以通过按Enter键运行
gdaltransform
,程序本身从其stdin而不是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
我猜您可以通过按Enter键运行
gdaltransform
,程序本身从其stdin而不是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
有什么原因不从Python中调用osr.CoordinateTransformation()吗?有什么原因不从Python中调用osr.CoordinateTransformation()吗?