通常命令行实用程序可以将其参数作为命令行参数接收,但是sir\util2通过C运行时函数^{}1从stdin读取用户输入。子进程便利函数call、check_call和{}不便于向stdin发送输入。直接使用Popen类,然后使用communicate。在
我手动跟踪源文件sir_util2.c中的fscanf调用,得出以下结果:import subprocess
sir_util2_path = 'sir_util2.exe'
def sir_to_geotiff(infname, outfname, smin, smax, show_nodata):
show_nodata = int(show_nodata)
opt = 6 # convert to image
fmt = 3 # GeoTIFF
param = [infname, opt, fmt, smin, smax, show_nodata, outfname]
cmd = [sir_util2_path]
p = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
out, err = p.communicate('\n'.join(map(str, param)))
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode,
cmd,
output=(out,err))
我使用了一个小的测试程序来代替编译原始源代码,所以