使用Python命令modu的多行shell命令

2024-09-30 03:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个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_0=-118 +x_0=2000000 +y_0=500000 +ellps=GRS80 
+units=m +no_defs\' -t_srs epsg:4326 \n' + str(x) + ' ' + str(y) )

我用'\n'试过了,但没用。在


Tags: 函数字符串命令shelltmpcommandsenterlat
2条回答

我的猜测是,通过按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
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(我刚才所说的)是,如果给定一个命令字符串而不是一个列表,那么就应该使用它。如果您想使用列表,建议如下:

^{pr2}$

然后捕获输出,或者您可以使用开放流并使用handle.stdin.write(),但这有点棘手。在

除非您只想执行、读和死,.communicate()是完美的,或者只是.check_output(<cmd>)

关于Popen如何工作的好信息可以在这里找到(尽管主题不同):python subprocess stdin.write a string error 22 invalid argument




解决方案

无论如何,这个应该起作用(您必须重定向STDIN和STDOUT):

from subprocess import *

c = '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'

handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
print handle.stdout.read()
handle.flush()

相关问题 更多 >

    热门问题