Python子流程公式

时间:2016-10-20 05:18:14

标签: python subprocess ogr

我一直在尝试使用Python的子进程模块。我希望效仿以下成功的命令:

命令行:

ogr2ogr -f GeoJSON -clipsrc cutting.json output.json input.json

Python实现:

import subprocess
subprocess.call(["ogr2ogr", "-f", "GeoJSON", "-clipsrc", "cutting.json", "output.json", "input.json"], shell=True)

然而,python脚本输出: FAILURE: no target datasource provided

从文档中,我可以看到语法是正确的,我正在以正确的顺序指定源和目标数据源。当然,由于它在命令行上工作,我倾向于认为数据方向是正确的。我是否错误地调用了子流程?

供参考,ogr2ogr用法:

Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update]
               [-select field_list] [-where restricted_where]
               [-progress] [-sql <sql statement>] [-dialect dialect]
               [-preserve_fid] [-fid FID]
               [-spat xmin ymin xmax ymax] [-geomfield field]
               [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]
               [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]
               dst_datasource_name src_datasource_name
               [-lco NAME=VALUE] [-nln name] [-nlt type] [-dim 2|3|layer_dim] [layer [layer ...]]

Advanced options :
               [-gt n]
               [-clipsrc [xmin ymin xmax ymax]|WKT|datasource|spat_extent]
               [-clipsrcsql sql_statement] [-clipsrclayer layer]
               [-clipsrcwhere expression]
               [-clipdst [xmin ymin xmax ymax]|WKT|datasource]
               [-clipdstsql sql_statement] [-clipdstlayer layer]
               [-clipdstwhere expression]
               [-wrapdateline][-datelineoffset val]
               [[-simplify tolerance] | [-segmentize max_dist]]
               [-addfields]
               [-relaxedFieldNameMatch]
               [-fieldTypeToString All|(type1[,type2]*)] [-unsetFieldWidth]
               [-fieldmap identity | index1[,index2]*]
               [-splitlistfields] [-maxsubfields val]
               [-explodecollections] [-zfield field_name]
               [-gcp pixel line easting northing [elevation]]* [-order n | -tps]

2 个答案:

答案 0 :(得分:2)

我个人在基于* nix的机器上使用类似下面的内容来完全从python脚本调度调用。也许它可以帮助你(或者你可以根据自己的需要定制它)。

import os, subprocess, time
name = 'ogr2ogr_{}'.format(time.time())
call = ['nohup', 'ogr2ogr', '-f', 'GeoJSON', '-clipsrc', 
        'cutting.json', 'output.json', 'input.json']
o_std = open(os.path.join('/my/log/dir', '{}.log'.format(name)), 'w')
o_err = open(os.path.join('/my/log/dir', '{}.err'.format(name)), 'w')
r = subprocess.Popen(call, stdout=o_std, stderr=o_err, preexec_fn=os.setpgrp)

如果您不想分派子流程,只需删除nohup列表项,不要将os.setpgrp设置为preexec_fn

答案 1 :(得分:0)

我通常使用subprocess来调用命令行,对于ogr2ogr我有一些工作方法是通过在调用中添加shell = True选项来实现:

ProcessToCall = [&#39; ogr2ogr&#39; +&#34; &#34 + STR(OutShp)+&#34; &#34 + STR(InShp)+&#34; &#34; +&#39; -dialect sqlite -sql&#34; SELECT ST_Union(geometry)AS geometry FROM&#39; +&#34; &#34 + STR(InShp).split(&#34;&#34;)[0] +&#39;&#34;&#39;] subprocess.call(ProcessToCall,壳=真)