使用Python脚本更高效地调用和执行带参数的函数并获得其标准输出

2024-09-30 01:22:41 发布

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

我正在编写一个脚本,它获取经度和纬度,并通过名为gdallocationinfo的可执行文件运行它们。可执行文件将纬度和经度作为参数,并返回其STDOUT作为该坐标的值。我一直在阅读有关子流程的文章,我想知道如果我想运行大量的点,这是否是实现这一点的最有效的方法。看来要花很长时间。在

def gdalgetpointdata(longitude,latitude):
    proc = subprocess.Popen(["gdallocationinfo","C:\Users\data\pop","-wgs84","-valonly","{0}".format(longitude),"{0}".format(latitude)], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    return int(out)

有没有更好的方法来调用这个可执行文件,而不必在每次运行函数时都生成一个新的子进程?我能做些什么来加快速度吗?在

另外,我知道,如果从命令行运行可执行文件,它将继续接受STDIN并在STDOUT中提供输出,直到您告诉它quit()


Tags: 方法脚本format可执行文件参数stdout流程proc
2条回答

该实用程序可以用一个调用执行多个坐标。例如,使用坐标对准备一个简单的coords.txt文本文件:

1.0 2.0
3.0 4.0
5.0 6.0

然后从一个OSGeo4W外壳将其导入并输出:

^{pr2}$

它将生成一个values.txt文件,其中包含每个坐标的值。可以使用管道stdin和stdout参数对Popen执行相同的操作。在

coords = [(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)]
coord_txt = ''.join(['{0} {1}\n'.format(*c) for c in coords])
p = subprocess.Popen(
    ['gdallocationinfo', r'C:\path\to\raster.tif', '-wgs84', '-valonly'],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, shell=True)
values_txt, err = p.communicate(coord_txt)
values = values_txt.splitlines()

values将是一个值列表,长度与coords相同。在

以下是@Mike T's answer的一个版本,它传递输入,动态读取输出(未测试):

#!/usr/bin/env python
from __future__ import print_function
from subprocess import Popen, PIPE
from threading import Thread

def pump_input(pipe, coords):
    with pipe:
        for longitude, latitude in coords:
            print(longitude, latitude, file=pipe)

p = Popen(['gdallocationinfo', r'C:\path\to\raster.tif', '-wgs84', '-valonly'],
          shell=True, #NOTE: don't use a list argument with shell=True on POSIX
          stdin=PIPE, stdout=PIPE, bufsize=-1,
          universal_newlines=True)
Thread(target=pump_input, args=[p.stdin, coords]).start()
with p.stdout:
    for line in p.stdout:
        print(int(line))
if p.wait() != 0:
   raise Error

使用use GDAL's Python bindings instead可能更有效。在

相关问题 更多 >

    热门问题