示例#1
0
def main(argv):
    if sys.version_info < (3, 0, 0):
        argv = [fn.decode(sys.getfilesystemencoding()) for fn in argv]
    argv = ogr.GeneralCmdLineProcessor(argv)
    if argv is None:
        return 1
    return process(argv[1:])
示例#2
0
def main(argv):
    argv = ogr.GeneralCmdLineProcessor(argv)

    ds_name = None
    lyr_name = None
    bAppend = False
    bOverwrite = False

    nArgc = len(argv)
    iArg = 1
    while iArg < nArgc:

        if argv[iArg] == '-append':
            bAppend = True

        elif argv[iArg] == '-overwrite':
            bOverwrite = True

        elif argv[iArg][0] == '-':
            return Usage()

        elif ds_name is None:
            ds_name = argv[iArg]

        elif lyr_name is None:
            lyr_name = argv[iArg]

        iArg = iArg + 1

    if ds_name is None:
        return Usage()

    if bAppend and bOverwrite:
        print('Only one of -append or -overwrite can be used')
        return 1

    ds = ogr.Open(ds_name, update=1)
    if ds is None:
        print('Cannot open %s in update mode' % ds_name)
        return 1

    ret = True
    if lyr_name is not None:
        ret = process_layer(ds, lyr_name, bAppend, bOverwrite)
    else:
        for i in range(ds.GetLayerCount()):
            if not process_layer(ds,
                                 ds.GetLayer(i).GetName(), bAppend,
                                 bOverwrite):
                ret = False
    ds = None

    if ret:
        return 0
    else:
        return 1
示例#3
0
def main(argv=None):

    global bReadOnly
    global bVerbose
    global bSummaryOnly
    global nFetchFID
    global papszOptions

    pszWHERE = None
    pszDataSource = None
    papszLayers = None
    poSpatialFilter = None
    nRepeatCount = 1
    bAllLayers = False
    pszSQLStatement = None
    pszDialect = None
    options = {}
    pszGeomField = None

    if argv is None:
        argv = sys.argv

    argv = ogr.GeneralCmdLineProcessor(argv)

    # --------------------------------------------------------------------
    #      Processing command line arguments.
    # --------------------------------------------------------------------
    if argv is None:
        return 1

    nArgc = len(argv)

    iArg = 1
    while iArg < nArgc:

        if EQUAL(argv[iArg], "--utility_version"):
            print("%s is running against GDAL %s" %
                  (argv[0], gdal.VersionInfo("RELEASE_NAME")))
            return 0

        elif EQUAL(argv[iArg], "-ro"):
            bReadOnly = True
        elif EQUAL(argv[iArg], "-q") or EQUAL(argv[iArg], "-quiet"):
            bVerbose = False
        elif EQUAL(argv[iArg], "-fid") and iArg < nArgc - 1:
            iArg = iArg + 1
            nFetchFID = int(argv[iArg])
        elif EQUAL(argv[iArg], "-spat") and iArg + 4 < nArgc:
            oRing = ogr.Geometry(ogr.wkbLinearRing)

            oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 2]))
            oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 4]))
            oRing.AddPoint(float(argv[iArg + 3]), float(argv[iArg + 4]))
            oRing.AddPoint(float(argv[iArg + 3]), float(argv[iArg + 2]))
            oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 2]))

            poSpatialFilter = ogr.Geometry(ogr.wkbPolygon)
            poSpatialFilter.AddGeometry(oRing)
            iArg = iArg + 4

        elif EQUAL(argv[iArg], "-geomfield") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszGeomField = argv[iArg]

        elif EQUAL(argv[iArg], "-where") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszWHERE = argv[iArg]

        elif EQUAL(argv[iArg], "-sql") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszSQLStatement = argv[iArg]

        elif EQUAL(argv[iArg], "-dialect") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszDialect = argv[iArg]

        elif EQUAL(argv[iArg], "-rc") and iArg < nArgc - 1:
            iArg = iArg + 1
            nRepeatCount = int(argv[iArg])

        elif EQUAL(argv[iArg], "-al"):
            bAllLayers = True

        elif EQUAL(argv[iArg], "-so") or EQUAL(argv[iArg], "-summary"):
            bSummaryOnly = True

        elif len(argv[iArg]) > 8 and EQUAL(argv[iArg][0:8], "-fields="):
            options['DISPLAY_FIELDS'] = argv[iArg][7:len(argv[iArg])]

        elif len(argv[iArg]) > 6 and EQUAL(argv[iArg][0:6], "-geom="):
            options['DISPLAY_GEOMETRY'] = argv[iArg][6:len(argv[iArg])]

        elif argv[iArg][0] == '-':
            return Usage()

        elif pszDataSource is None:
            pszDataSource = argv[iArg]
        else:
            if papszLayers is None:
                papszLayers = []
            papszLayers.append(argv[iArg])
            bAllLayers = False

        iArg = iArg + 1

    if pszDataSource is None:
        return Usage()

# --------------------------------------------------------------------
#      Open data source.
# --------------------------------------------------------------------
    poDS = None
    poDriver = None

    poDS = ogr.Open(pszDataSource, not bReadOnly)
    if poDS is None and not bReadOnly:
        poDS = ogr.Open(pszDataSource, False)
        if poDS is not None and bVerbose:
            print("Had to open data source read-only.")
            bReadOnly = True

# --------------------------------------------------------------------
#      Report failure.
# --------------------------------------------------------------------
    if poDS is None:
        print("FAILURE:\n"
              "Unable to open datasource `%s' with the following drivers." %
              pszDataSource)

        for iDriver in range(ogr.GetDriverCount()):
            print("  -> %s" % ogr.GetDriver(iDriver).GetName())

        return 1

    poDriver = poDS.GetDriver()

    # --------------------------------------------------------------------
    #      Some information messages.
    # --------------------------------------------------------------------
    if bVerbose:
        print("INFO: Open of `%s'\n"
              "      using driver `%s' successful." %
              (pszDataSource, poDriver.GetName()))

    poDS_Name = poDS.GetName()
    if str(type(pszDataSource)) == "<type 'unicode'>" and str(
            type(poDS_Name)) == "<type 'str'>":
        poDS_Name = poDS_Name.decode("utf8")
    if bVerbose and pszDataSource != poDS_Name:
        print("INFO: Internal data source name `%s'\n"
              "      different from user name `%s'." %
              (poDS_Name, pszDataSource))

# --------------------------------------------------------------------
#      Special case for -sql clause.  No source layers required.
# --------------------------------------------------------------------
    if pszSQLStatement is not None:
        poResultSet = None

        nRepeatCount = 0  #// skip layer reporting.

        if papszLayers is not None:
            print("layer names ignored in combination with -sql.")

        if pszGeomField is None:
            poResultSet = poDS.ExecuteSQL(pszSQLStatement, poSpatialFilter,
                                          pszDialect)
        else:
            poResultSet = poDS.ExecuteSQL(pszSQLStatement, None, pszDialect)

        if poResultSet is not None:
            if pszWHERE is not None:
                if poResultSet.SetAttributeFilter(pszWHERE) != 0:
                    print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE)
                    return 1

            if pszGeomField is not None:
                ReportOnLayer(poResultSet, None, pszGeomField, poSpatialFilter,
                              options)
            else:
                ReportOnLayer(poResultSet, None, None, None, options)
            poDS.ReleaseResultSet(poResultSet)

    #gdal.Debug( "OGR", "GetLayerCount() = %d\n", poDS.GetLayerCount() )

    for iRepeat in range(nRepeatCount):
        if papszLayers is None:
            # --------------------------------------------------------------------
            #      Process each data source layer.
            # --------------------------------------------------------------------
            for iLayer in range(poDS.GetLayerCount()):
                poLayer = poDS.GetLayer(iLayer)

                if poLayer is None:
                    print("FAILURE: Couldn't fetch advertised layer %d!" %
                          iLayer)
                    return 1

                if not bAllLayers:
                    line = "%d: %s" % (iLayer + 1,
                                       poLayer.GetLayerDefn().GetName())

                    nGeomFieldCount = poLayer.GetLayerDefn().GetGeomFieldCount(
                    )
                    if nGeomFieldCount > 1:
                        line = line + " ("
                        for iGeom in range(nGeomFieldCount):
                            if iGeom > 0:
                                line = line + ", "
                            poGFldDefn = poLayer.GetLayerDefn(
                            ).GetGeomFieldDefn(iGeom)
                            line = line + "%s" % ogr.GeometryTypeToName(
                                poGFldDefn.GetType())
                        line = line + ")"

                    if poLayer.GetLayerDefn().GetGeomType() != ogr.wkbUnknown:
                        line = line + " (%s)" % ogr.GeometryTypeToName(
                            poLayer.GetLayerDefn().GetGeomType())

                    print(line)
                else:
                    if iRepeat != 0:
                        poLayer.ResetReading()

                    ReportOnLayer(poLayer, pszWHERE, pszGeomField,
                                  poSpatialFilter, options)

        else:
            # --------------------------------------------------------------------
            #      Process specified data source layers.
            # --------------------------------------------------------------------
            for papszIter in papszLayers:
                poLayer = poDS.GetLayerByName(papszIter)

                if poLayer is None:
                    print("FAILURE: Couldn't fetch requested layer %s!" %
                          papszIter)
                    return 1

                if iRepeat != 0:
                    poLayer.ResetReading()

                ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter,
                              options)

# --------------------------------------------------------------------
#      Close down.
# --------------------------------------------------------------------
    poDS.Destroy()

    return 0
示例#4
0
def main(args=None, progress_func=TermProgress, progress_data=None):

    global bSkipFailures
    global nGroupTransactions
    global bPreserveFID
    global nFIDToFetch

    pszFormat = "ESRI Shapefile"
    pszDataSource = None
    pszDestDataSource = None
    papszLayers = []
    papszDSCO = []
    papszLCO = []
    bTransform = False
    bAppend = False
    bUpdate = False
    bOverwrite = False
    pszOutputSRSDef = None
    pszSourceSRSDef = None
    poOutputSRS = None
    poSourceSRS = None
    pszNewLayerName = None
    pszWHERE = None
    poSpatialFilter = None
    pszSelect = None
    papszSelFields = None
    pszSQLStatement = None
    eGType = -2
    eGeomOp = GeomOperation.NONE
    dfGeomOpParam = 0
    papszFieldTypesToString = []
    bDisplayProgress = False
    pfnProgress = None
    pProgressData = None
    bClipSrc = False
    poClipSrc = None
    pszClipSrcDS = None
    pszClipSrcSQL = None
    pszClipSrcLayer = None
    pszClipSrcWhere = None
    poClipDst = None
    pszClipDstDS = None
    pszClipDstSQL = None
    pszClipDstLayer = None
    pszClipDstWhere = None
    pszSrcEncoding = None
    pszDstEncoding = None
    bExplodeCollections = False
    pszZField = None

    if args is None:
        args = sys.argv

    args = ogr.GeneralCmdLineProcessor(args)

    #/* -------------------------------------------------------------------- */
    #/*      Processing command line arguments.                              */
    #/* -------------------------------------------------------------------- */
    if args is None:
        return False

    nArgc = len(args)

    iArg = 1
    while iArg < nArgc:
        if EQUAL(args[iArg], "-f") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszFormat = args[iArg]

        elif EQUAL(args[iArg], "-dsco") and iArg < nArgc - 1:
            iArg = iArg + 1
            papszDSCO.append(args[iArg])

        elif EQUAL(args[iArg], "-lco") and iArg < nArgc - 1:
            iArg = iArg + 1
            papszLCO.append(args[iArg])

        elif EQUAL(args[iArg], "-preserve_fid"):
            bPreserveFID = True

        elif len(args[iArg]) >= 5 and EQUAL(args[iArg][0:5], "-skip"):
            bSkipFailures = True
            nGroupTransactions = 1  # /* #2409 */

        elif EQUAL(args[iArg], "-append"):
            bAppend = True
            bUpdate = True

        elif EQUAL(args[iArg], "-overwrite"):
            bOverwrite = True
            bUpdate = True

        elif EQUAL(args[iArg], "-update"):
            bUpdate = True

        elif EQUAL(args[iArg], "-fid") and iArg < nArgc - 1:
            iArg = iArg + 1
            nFIDToFetch = int(args[iArg])

        elif EQUAL(args[iArg], "-sql") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszSQLStatement = args[iArg]

        elif EQUAL(args[iArg], "-nln") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszNewLayerName = args[iArg]

        elif EQUAL(args[iArg], "-nlt") and iArg < nArgc - 1:

            if EQUAL(args[iArg + 1], "NONE"):
                eGType = ogr.wkbNone
            elif EQUAL(args[iArg + 1], "GEOMETRY"):
                eGType = ogr.wkbUnknown
            elif EQUAL(args[iArg + 1], "POINT"):
                eGType = ogr.wkbPoint
            elif EQUAL(args[iArg + 1], "LINESTRING"):
                eGType = ogr.wkbLineString
            elif EQUAL(args[iArg + 1], "POLYGON"):
                eGType = ogr.wkbPolygon
            elif EQUAL(args[iArg + 1], "GEOMETRYCOLLECTION"):
                eGType = ogr.wkbGeometryCollection
            elif EQUAL(args[iArg + 1], "MULTIPOINT"):
                eGType = ogr.wkbMultiPoint
            elif EQUAL(args[iArg + 1], "MULTILINESTRING"):
                eGType = ogr.wkbMultiLineString
            elif EQUAL(args[iArg + 1], "MULTIPOLYGON"):
                eGType = ogr.wkbMultiPolygon
            elif EQUAL(args[iArg + 1], "GEOMETRY25D"):
                eGType = ogr.wkbUnknown | ogr.wkb25DBit
            elif EQUAL(args[iArg + 1], "POINT25D"):
                eGType = ogr.wkbPoint25D
            elif EQUAL(args[iArg + 1], "LINESTRING25D"):
                eGType = ogr.wkbLineString25D
            elif EQUAL(args[iArg + 1], "POLYGON25D"):
                eGType = ogr.wkbPolygon25D
            elif EQUAL(args[iArg + 1], "GEOMETRYCOLLECTION25D"):
                eGType = ogr.wkbGeometryCollection25D
            elif EQUAL(args[iArg + 1], "MULTIPOINT25D"):
                eGType = ogr.wkbMultiPoint25D
            elif EQUAL(args[iArg + 1], "MULTILINESTRING25D"):
                eGType = ogr.wkbMultiLineString25D
            elif EQUAL(args[iArg + 1], "MULTIPOLYGON25D"):
                eGType = ogr.wkbMultiPolygon25D
            else:
                print("-nlt %s: type not recognised." % args[iArg + 1])
                return False

            iArg = iArg + 1

        elif (EQUAL(args[iArg],"-tg") or \
                EQUAL(args[iArg],"-gt")) and iArg < nArgc-1:
            iArg = iArg + 1
            nGroupTransactions = int(args[iArg])

        elif EQUAL(args[iArg], "-s_srs") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszSourceSRSDef = args[iArg]

        elif EQUAL(args[iArg], "-a_srs") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszOutputSRSDef = args[iArg]

        elif EQUAL(args[iArg], "-t_srs") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszOutputSRSDef = args[iArg]
            bTransform = True

        elif EQUAL(args[iArg], "-spat") and iArg + 4 < nArgc:
            oRing = ogr.Geometry(ogr.wkbLinearRing)

            oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2]))
            oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 4]))
            oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 4]))
            oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 2]))
            oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2]))

            poSpatialFilter = ogr.Geometry(ogr.wkbPolygon)
            poSpatialFilter.AddGeometry(oRing)
            iArg = iArg + 4

        elif EQUAL(args[iArg], "-where") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszWHERE = args[++iArg]

        elif EQUAL(args[iArg], "-select") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszSelect = args[iArg]
            if pszSelect.find(',') != -1:
                papszSelFields = pszSelect.split(',')
            else:
                papszSelFields = pszSelect.split(' ')
            if papszSelFields[0] == '':
                papszSelFields = []

        elif EQUAL(args[iArg], "-simplify") and iArg < nArgc - 1:
            iArg = iArg + 1
            eGeomOp = GeomOperation.SIMPLIFY_PRESERVE_TOPOLOGY
            dfGeomOpParam = float(args[iArg])

        elif EQUAL(args[iArg], "-segmentize") and iArg < nArgc - 1:
            iArg = iArg + 1
            eGeomOp = GeomOperation.SEGMENTIZE
            dfGeomOpParam = float(args[iArg])

        elif EQUAL(args[iArg], "-fieldTypeToString") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszFieldTypeToString = args[iArg]
            if pszFieldTypeToString.find(',') != -1:
                tokens = pszFieldTypeToString.split(',')
            else:
                tokens = pszFieldTypeToString.split(' ')

            for token in tokens:
                if EQUAL(token,"Integer") or \
                    EQUAL(token,"Real") or \
                    EQUAL(token,"String") or \
                    EQUAL(token,"Date") or \
                    EQUAL(token,"Time") or \
                    EQUAL(token,"DateTime") or \
                    EQUAL(token,"Binary") or \
                    EQUAL(token,"IntegerList") or \
                    EQUAL(token,"RealList") or \
                    EQUAL(token,"StringList"):

                    papszFieldTypesToString.append(token)

                elif EQUAL(token, "All"):
                    papszFieldTypesToString = ['All']
                    break

                else:
                    print("Unhandled type for fieldtypeasstring option : %s " %
                          token)
                    return Usage()

        elif EQUAL(args[iArg], "-progress"):
            bDisplayProgress = True

        #/*elif EQUAL(args[iArg],"-wrapdateline") )
        #{
        #    bWrapDateline = True;
        #}
        #*/
        elif EQUAL(args[iArg], "-clipsrc") and iArg < nArgc - 1:

            bClipSrc = True
            if IsNumber(args[iArg + 1]) and iArg < nArgc - 4:
                oRing = ogr.Geometry(ogr.wkbLinearRing)

                oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2]))
                oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 4]))
                oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 4]))
                oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 2]))
                oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2]))

                poClipSrc = ogr.Geometry(ogr.wkbPolygon)
                poClipSrc.AddGeometry(oRing)
                iArg = iArg + 4

            elif (len(args[iArg+1]) >= 7 and EQUAL(args[iArg+1][0:7],"POLYGON") ) or \
                  (len(args[iArg+1]) >= 12 and EQUAL(args[iArg+1][0:12],"MULTIPOLYGON") ) :
                poClipSrc = ogr.CreateGeometryFromWkt(args[iArg + 1])
                if poClipSrc is None:
                    print(
                        "FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n"
                    )
                    return Usage()

                iArg = iArg + 1

            elif EQUAL(args[iArg + 1], "spat_extent"):
                iArg = iArg + 1

            else:
                pszClipSrcDS = args[iArg + 1]
                iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipsrcsql") and iArg < nArgc - 1:
            pszClipSrcSQL = args[iArg + 1]
            iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipsrclayer") and iArg < nArgc - 1:
            pszClipSrcLayer = args[iArg + 1]
            iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipsrcwhere") and iArg < nArgc - 1:
            pszClipSrcWhere = args[iArg + 1]
            iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipdst") and iArg < nArgc - 1:

            if IsNumber(args[iArg + 1]) and iArg < nArgc - 4:
                oRing = ogr.Geometry(ogr.wkbLinearRing)

                oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2]))
                oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 4]))
                oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 4]))
                oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 2]))
                oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2]))

                poClipDst = ogr.Geometry(ogr.wkbPolygon)
                poClipDst.AddGeometry(oRing)
                iArg = iArg + 4

            elif (len(args[iArg+1]) >= 7 and EQUAL(args[iArg+1][0:7],"POLYGON") ) or \
                  (len(args[iArg+1]) >= 12 and EQUAL(args[iArg+1][0:12],"MULTIPOLYGON") ) :
                poClipDst = ogr.CreateGeometryFromWkt(args[iArg + 1])
                if poClipDst is None:
                    print(
                        "FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n"
                    )
                    return Usage()

                iArg = iArg + 1

            elif EQUAL(args[iArg + 1], "spat_extent"):
                iArg = iArg + 1

            else:
                pszClipDstDS = args[iArg + 1]
                iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipdstsql") and iArg < nArgc - 1:
            pszClipDstSQL = args[iArg + 1]
            iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipdstlayer") and iArg < nArgc - 1:
            pszClipDstLayer = args[iArg + 1]
            iArg = iArg + 1

        elif EQUAL(args[iArg], "-clipdstwhere") and iArg < nArgc - 1:
            pszClipDstWhere = args[iArg + 1]
            iArg = iArg + 1

        elif EQUAL(args[iArg], "-explodecollections"):
            bExplodeCollections = True

        elif EQUAL(args[iArg], "-zfield") and iArg < nArgc - 1:
            pszZField = args[iArg + 1]
            iArg = iArg + 1

        elif args[iArg][0] == '-':
            return Usage()

        elif pszDestDataSource is None:
            pszDestDataSource = args[iArg]
        elif pszDataSource is None:
            pszDataSource = args[iArg]
        else:
            papszLayers.append(args[iArg])

        iArg = iArg + 1

    if pszDataSource is None:
        return Usage()

    if pszDestDataSource is None:
        return Usage()

    inds = gdal.Open(pszDataSource, GA_ReadOnly)
    if inds is None:
        print "Open of input file failed.\n"
        sys.exit(1)

    drv = ogr.GetDriverByName(pszFormat)
    if drv is None:
        print "%s driver not available.\n" % pszFormat
        sys.exit(1)

    outds = drv.CreateDataSource(pszDestDataSource)
    if outds is None:
        print "Creation of output file failed.\n"
        sys.exit(1)

    lyr = outds.CreateLayer("layer", None, ogr.wkbPoint)
    if lyr is None:
        print "Layer creation failed.\n"
        sys.exit(1)

    field_defn = ogr.FieldDefn("Value", ogr.OFTString)
    field_defn.SetWidth(32)

    if lyr.CreateField(field_defn) != 0:
        print "Creating Name field failed.\n"
        sys.exit(1)

    gt = inds.GetGeoTransform()
    #    if gt is not None and gt != (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
    #    outdataset.SetGeoTransform(gt)

    prj = inds.GetProjectionRef()
    print 'prj: ' + str(prj)
    if prj is not None and len(prj) > 0:
        outds.SetProjection(prj)

#/* -------------------------------------------------------------------- */
#/*      Close down.                                                     */
#/* -------------------------------------------------------------------- */
#/* We must explicetely destroy the output dataset in order the file */
#/* to be properly closed ! */
    outds.Destroy()
    #inds.Destroy()
    inds = None

    return True
示例#5
0
文件: ogrmerge.py 项目: edzer/gdal
def main(argv=sys.argv):
    argv = ogr.GeneralCmdLineProcessor(argv)
    if argv is None:
        return 1
    return process(argv[1:])
示例#6
0
        return False
    lyr_defn = lyr.GetLayerDefn()

    if lyr_defn.GetFieldIndex('gml_id') < 0:
        return True

    ret = True
    for ifield in range(lyr_defn.GetFieldCount()):
        if lyr_defn.GetFieldDefn(ifield).GetName().endswith("_href"):
            if not build_junction_table(ds, lyr, ifield, bAppend, bOverwrite):
                ret = False
    return ret


argv = sys.argv
argv = ogr.GeneralCmdLineProcessor(argv)

ds_name = None
lyr_name = None
bAppend = False
bOverwrite = False

nArgc = len(argv)
iArg = 1
while iArg < nArgc:

    if argv[iArg] == '-append':
        bAppend = True

    elif argv[iArg] == '-overwrite':
        bOverwrite = True
示例#7
0
def main(argv=None):

    format = 'ESRI Shapefile'
    quiet_flag = 0
    input_ds_name = None
    input_lyr_name = None
    method_ds_name = None
    method_lyr_name = None
    output_ds_name = None
    output_lyr_name = None
    op_str = None
    dsco = []
    lco = []
    opt = []
    overwrite = False
    input_fields = 'ALL'
    method_fields = 'ALL'
    geom_type = ogr.wkbUnknown
    srs_name = None
    srs = None

    argv = ogr.GeneralCmdLineProcessor(sys.argv)
    if argv is None:
        return 1

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-f' and i + 1 < len(argv):
            i = i + 1
            format = argv[i]

        elif arg == '-input_ds' and i + 1 < len(argv):
            i = i + 1
            input_ds_name = argv[i]

        elif arg == '-input_lyr' and i + 1 < len(argv):
            i = i + 1
            input_lyr_name = argv[i]

        elif arg == '-method_ds' and i + 1 < len(argv):
            i = i + 1
            method_ds_name = argv[i]

        elif arg == '-method_lyr' and i + 1 < len(argv):
            i = i + 1
            method_lyr_name = argv[i]

        elif arg == '-output_ds' and i + 1 < len(argv):
            i = i + 1
            output_ds_name = argv[i]

        elif arg == '-output_lyr' and i + 1 < len(argv):
            i = i + 1
            output_lyr_name = argv[i]

        elif arg == '-input_fields' and i + 1 < len(argv):
            i = i + 1
            if EQUAL(argv[i], "NONE"):
                input_fields = "NONE"
            elif EQUAL(argv[i], "ALL"):
                input_fields = "ALL"
            else:
                input_fields = argv[i].split(',')

        elif arg == '-method_fields' and i + 1 < len(argv):
            i = i + 1
            if EQUAL(argv[i], "NONE"):
                method_fields = "NONE"
            elif EQUAL(argv[i], "ALL"):
                method_fields = "ALL"
            else:
                method_fields = argv[i].split(',')

        elif arg == '-dsco' and i + 1 < len(argv):
            i = i + 1
            dsco.append(argv[i])

        elif arg == '-lco' and i + 1 < len(argv):
            i = i + 1
            lco.append(argv[i])

        elif arg == '-opt' and i + 1 < len(argv):
            i = i + 1
            opt.append(argv[i])

        elif arg == "-nlt" and i + 1 < len(argv):
            i = i + 1
            val = argv[i]

            if EQUAL(val, "NONE"):
                geom_type = ogr.wkbNone
            elif EQUAL(val, "GEOMETRY"):
                geom_type = ogr.wkbUnknown
            elif EQUAL(val, "POINT"):
                geom_type = ogr.wkbPoint
            elif EQUAL(val, "LINESTRING"):
                geom_type = ogr.wkbLineString
            elif EQUAL(val, "POLYGON"):
                geom_type = ogr.wkbPolygon
            elif EQUAL(val, "GEOMETRYCOLLECTION"):
                geom_type = ogr.wkbGeometryCollection
            elif EQUAL(val, "MULTIPOINT"):
                geom_type = ogr.wkbMultiPoint
            elif EQUAL(val, "MULTILINESTRING"):
                geom_type = ogr.wkbMultiLineString
            elif EQUAL(val, "MULTIPOLYGON"):
                geom_type = ogr.wkbMultiPolygon
            elif EQUAL(val, "GEOMETRY25D"):
                geom_type = ogr.wkbUnknown | ogr.wkb25DBit
            elif EQUAL(val, "POINT25D"):
                geom_type = ogr.wkbPoint25D
            elif EQUAL(val, "LINESTRING25D"):
                geom_type = ogr.wkbLineString25D
            elif EQUAL(val, "POLYGON25D"):
                geom_type = ogr.wkbPolygon25D
            elif EQUAL(val, "GEOMETRYCOLLECTION25D"):
                geom_type = ogr.wkbGeometryCollection25D
            elif EQUAL(val, "MULTIPOINT25D"):
                geom_type = ogr.wkbMultiPoint25D
            elif EQUAL(val, "MULTILINESTRING25D"):
                geom_type = ogr.wkbMultiLineString25D
            elif EQUAL(val, "MULTIPOLYGON25D"):
                geom_type = ogr.wkbMultiPolygon25D
            else:
                print("-nlt %s: type not recognised." % val)
                return 1

        elif arg == "-a_srs" and i + 1 < len(argv):
            i = i + 1
            srs_name = argv[i]

        elif EQUAL(arg, "Union"):
            op_str = "Union"

        elif EQUAL(arg, "Intersection"):
            op_str = "Intersection"

        elif EQUAL(arg, "SymDifference"):
            op_str = "SymDifference"

        elif EQUAL(arg, "Identity"):
            op_str = "Identity"

        elif EQUAL(arg, "Update"):
            op_str = "Update"

        elif EQUAL(arg, "Clip"):
            op_str = "Clip"

        elif EQUAL(arg, "Erase"):
            op_str = "Erase"

        elif arg == "-overwrite":
            overwrite = True

        elif arg == '-q' or arg == '-quiet':
            quiet_flag = 1

        else:
            return Usage()

        i = i + 1

    if input_ds_name is None or \
       method_ds_name is None or \
       output_ds_name is None or \
       op_str is None:
        return Usage()

    if input_fields == 'NONE' and method_fields == 'NONE':
        print(
            'Warning: -input_fields NONE and -method_fields NONE results in all fields being added'
        )

    # Input layer
    input_ds = ogr.Open(input_ds_name)
    if input_ds is None:
        print('Cannot open input dataset : %s' % input_ds_name)
        return 1

    if input_lyr_name is None:
        cnt = input_ds.GetLayerCount()
        if cnt != 1:
            print(
                'Input datasource has not a single layer, so you should specify its name with -input_lyr'
            )
            return 1
        input_lyr = input_ds.GetLayer(0)
    else:
        input_lyr = input_ds.GetLayerByName(input_lyr_name)
    if input_lyr is None:
        print('Cannot find input layer "%s"' % input_lyr_name)
        return 1

    # Method layer
    method_ds = ogr.Open(method_ds_name)
    if method_ds is None:
        print('Cannot open method dataset : %s' % method_ds_name)
        return 1

    if method_lyr_name is None:
        cnt = method_ds.GetLayerCount()
        if cnt != 1:
            print(
                'Method datasource has not a single layer, so you should specify its name with -method_lyr'
            )
            return 1
        method_lyr = method_ds.GetLayer(0)
    else:
        method_lyr = method_ds.GetLayerByName(method_lyr_name)
    if method_lyr is None:
        print('Cannot find method layer "%s"' % method_lyr_name)
        return 1

    # SRS
    if srs_name is not None:
        if not EQUAL(srs_name, "NULL") and not EQUAL(srs_name, "NONE"):
            srs = osr.SpatialReference()
            if srs.SetFromUserInput(srs_name) != 0:
                print("Failed to process SRS definition: %s" % srs_name)
                return 1
    else:
        srs = input_lyr.GetSpatialRef()
        srs2 = method_lyr.GetSpatialRef()
        if srs is None and srs2 is not None:
            print(
                'Warning: input layer has no SRS defined, but method layer has one.'
            )
        elif srs is not None and srs2 is None:
            print(
                'Warning: input layer has a SRS defined, but method layer has not one.'
            )
        elif srs is not None and srs2 is not None and srs.IsSame(srs2) != 1:
            print(
                'Warning: input and method layers have SRS defined, but they are not identical. No on-the-fly reprojection will be done.'
            )

    # Result layer
    output_ds = ogr.Open(output_ds_name, update=1)
    if output_ds is None:
        output_ds = ogr.Open(output_ds_name)
        if output_ds is not None:
            print(
                'Output datasource "%s" exists, but cannot be opened in update mode'
                % output_ds_name)
            return 1

        drv = ogr.GetDriverByName(format)
        if drv is None:
            print('Cannot find driver %s' % format)
            return 1

        output_ds = drv.CreateDataSource(output_ds_name, options=dsco)
        if output_ds is None:
            print('Cannot create datasource "%s"' % output_ds_name)
            return 1

        # Special case
        if EQUAL(drv.GetName(), "ESRI Shapefile") and output_lyr_name is None \
           and EQUAL(os.path.splitext(output_ds_name)[1], ".SHP"):
            output_lyr_name = os.path.splitext(
                os.path.basename(output_ds_name))[0]

        if output_lyr_name is None:
            print('-output_lyr should be specified')
            return 1

        output_lyr = CreateLayer(output_ds, output_lyr_name, srs, geom_type,
                                 lco, input_lyr, input_fields, method_lyr,
                                 method_fields, opt)
        if output_lyr is None:
            return 1
    else:
        drv = output_ds.GetDriver()

        if output_lyr_name is None:
            cnt = output_ds.GetLayerCount()
            if cnt != 1:
                print(
                    'Result datasource has not a single layer, so you should specify its name with -output_lyr'
                )
                return 1
            output_lyr = output_ds.GetLayer(0)
            output_lyr_name = output_lyr.GetName()
        else:
            output_lyr = output_ds.GetLayerByName(output_lyr_name)

            if output_lyr is None:
                if EQUAL(drv.GetName(), "ESRI Shapefile") and \
                   EQUAL(os.path.splitext(output_ds_name)[1], ".SHP") and \
                   not EQUAL(output_lyr_name, os.path.splitext(os.path.basename(output_ds_name))[0]):
                    print(
                        'Cannot create layer "%s" in a shapefile called "%s"' %
                        (output_lyr_name, output_ds_name))
                    return 1

                output_lyr = CreateLayer(output_ds, output_lyr_name, srs,
                                         geom_type, lco, input_lyr,
                                         input_fields, method_lyr,
                                         method_fields, opt)
                if output_lyr is None:
                    return 1

        if overwrite:
            cnt = output_ds.GetLayerCount()
            for iLayer in range(cnt):
                poLayer = output_ds.GetLayer(iLayer)
                if poLayer is not None \
                    and poLayer.GetName() == output_lyr_name:
                    break
            if iLayer != cnt:
                if output_ds.DeleteLayer(iLayer) != 0:
                    print("DeleteLayer() failed when overwrite requested.")
                    return 1

                output_lyr = CreateLayer(output_ds, output_lyr_name, srs,
                                         geom_type, lco, input_lyr,
                                         input_fields, method_lyr,
                                         method_fields, opt)
                if output_lyr is None:
                    return 1

    op = getattr(input_lyr, op_str)
    if quiet_flag == 0:
        ret = op(method_lyr,
                 output_lyr,
                 options=opt,
                 callback=gdal.TermProgress_nocb)
    else:
        ret = op(method_lyr, output_lyr, options=opt)

    input_ds = None
    method_ds = None
    output_ds = None

    if ret != 0:
        print('An error occured during %s operation' % op_str)
        return 1

    return 0
def main(argv):
    argv = ogr.GeneralCmdLineProcessor(argv)
    return ogrupdate_analyse_args(argv[1:])
def main(argv=None):

    bVerbose = True
    bSummaryOnly = False
    nFetchFID = ogr.NullFID

    pszWHERE = None
    pszDataSource = None
    papszLayers = None
    poSpatialFilter = None
    nRepeatCount = 1
    bAllLayers = False
    pszSQLStatement = None
    pszDialect = None
    options = {}
    pszGeomField = None

    if argv is None:
        argv = sys.argv

    argv = ogr.GeneralCmdLineProcessor(argv)

    #/* -------------------------------------------------------------------- */
    #/*      Processing command line arguments.                              */
    #/* -------------------------------------------------------------------- */
    if argv is None:
        return 1

    nArgc = len(argv)

    iArg = 1
    while iArg < nArgc:

        if EQUAL(argv[iArg], "--utility_version"):
            print("%s is running against GDAL %s" %
                  (argv[0], gdal.VersionInfo("RELEASE_NAME")))
            return 0

        elif EQUAL(argv[iArg], "-ro"):
            bReadOnly = True
        elif EQUAL(argv[iArg], "-q") or EQUAL(argv[iArg], "-quiet"):
            bVerbose = False
        elif EQUAL(argv[iArg], "-fid") and iArg < nArgc - 1:
            iArg = iArg + 1
            nFetchFID = int(argv[iArg])
        elif EQUAL(argv[iArg], "-spat") and iArg + 4 < nArgc:
            oRing = ogr.Geometry(ogr.wkbLinearRing)

            oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 2]))
            oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 4]))
            oRing.AddPoint(float(argv[iArg + 3]), float(argv[iArg + 4]))
            oRing.AddPoint(float(argv[iArg + 3]), float(argv[iArg + 2]))
            oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 2]))

            poSpatialFilter = ogr.Geometry(ogr.wkbPolygon)
            poSpatialFilter.AddGeometry(oRing)
            iArg = iArg + 4

        elif EQUAL(argv[iArg], "-geomfield") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszGeomField = argv[iArg]

        elif EQUAL(argv[iArg], "-where") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszWHERE = argv[iArg]

        elif EQUAL(argv[iArg], "-sql") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszSQLStatement = argv[iArg]

        elif EQUAL(argv[iArg], "-dialect") and iArg < nArgc - 1:
            iArg = iArg + 1
            pszDialect = argv[iArg]

        elif EQUAL(argv[iArg], "-rc") and iArg < nArgc - 1:
            iArg = iArg + 1
            nRepeatCount = int(argv[iArg])

        elif EQUAL(argv[iArg], "-al"):
            bAllLayers = True

        elif EQUAL(argv[iArg], "-so") or EQUAL(argv[iArg], "-summary"):
            bSummaryOnly = True

        elif len(argv[iArg]) > 8 and EQUAL(argv[iArg][0:8], "-fields="):
            options['DISPLAY_FIELDS'] = argv[iArg][7:len(argv[iArg])]

        elif len(argv[iArg]) > 6 and EQUAL(argv[iArg][0:6], "-geom="):
            options['DISPLAY_GEOMETRY'] = argv[iArg][6:len(argv[iArg])]

        elif argv[iArg][0] == '-':
            return Usage()

        elif pszDataSource is None:
            pszDataSource = argv[iArg]
        else:
            if papszLayers is None:
                papszLayers = []
            papszLayers.append(argv[iArg])
            bAllLayers = False

        iArg = iArg + 1

    if pszDataSource is None:
        return Usage()

    return ogrinfo(bReadOnly, bVerbose, bSummaryOnly, nFetchFID, pszWHERE,
                   pszDataSource, papszLayers, poSpatialFilter, nRepeatCount,
                   bAllLayers, pszSQLStatement, pszDialect, options,
                   pszGeomField)
示例#10
0
def main(argv=sys.argv):
    argv = ogr.GeneralCmdLineProcessor(argv)
    return ogr_dispatch(argv[1:])
示例#11
0
def main(argv=sys.argv):
    argv = ogr.GeneralCmdLineProcessor(argv)

    ogr_ds_name = None
    lyr_name = None

    tileitem = 'location'
    tilesrs = None
    srsname = None

    nArgc = len(argv)
    iArg = 1
    while iArg < nArgc:

        if argv[iArg] == "-lyr_name" and iArg < nArgc - 1:
            iArg = iArg + 1
            lyr_name = argv[iArg]

        elif argv[iArg] == "-tileindex" and iArg < nArgc - 1:
            iArg = iArg + 1
            tileitem = argv[iArg]

        elif argv[iArg] == "-src_srs_name" and iArg < nArgc - 1:
            iArg = iArg + 1
            tilesrs = argv[iArg]

        elif argv[iArg] == "-t_srs" and iArg < nArgc - 1:
            iArg = iArg + 1
            srsname = argv[iArg]

        elif argv[iArg][0] == '-':
            return Usage()

        elif ogr_ds_name is None:
            ogr_ds_name = argv[iArg]

        iArg = iArg + 1

    if ogr_ds_name is None or tilesrs is None:
        return Usage()

    ogr_ds = ogr.Open(ogr_ds_name)
    if ogr_ds is None:
        raise Exception('cannot open %s' % ogr_ds_name)
    if ogr_ds.GetLayerCount() == 1:
        lyr = ogr_ds.GetLayer(0)
    elif lyr_name is None:
        raise Exception('-lyr_name should be specified')
    else:
        lyr = ogr_ds.GetLayerByName(lyr_name)

    if lyr.GetLayerDefn().GetFieldIndex(tileitem) < 0:
        raise Exception('%s field cannot be found in layer definition' %
                        tileitem)

    if lyr.GetLayerDefn().GetFieldIndex(tilesrs) < 0:
        raise Exception('%s field cannot be found in layer definition' %
                        tilesrs)

    lyr_srs = lyr.GetSpatialRef()
    if srsname is not None:
        srs = osr.SpatialReference()
        if srs.SetFromUserInput(srsname) != 0:
            raise Exception('invalid value for -t_srs : %s' % srsname)

        # Sanity check
        if lyr_srs is not None:
            lyr_srs_proj4 = lyr_srs.ExportToProj4()
            lyr_srs = osr.SpatialReference()
            lyr_srs.SetFromUserInput(lyr_srs_proj4)
            lyr_srs_proj4 = lyr_srs.ExportToProj4()

            srs_proj4 = srs.ExportToProj4()
            if lyr_srs_proj4 != srs_proj4:
                raise Exception(
                    '-t_srs overrides the layer SRS in an incompatible way : (%s, %s)'
                    % (srs_proj4, lyr_srs_proj4))
    else:
        srs = lyr_srs

    if srs is None:
        raise Exception('cannot fetch source SRS')

    srs.AutoIdentifyEPSG()
    authority_name = srs.GetAuthorityName(None)
    authority_code = srs.GetAuthorityCode(None)
    dst_wkt = srs.ExportToWkt()
    if authority_name != 'EPSG' or authority_code is None:
        raise Exception('cannot fetch source SRS as EPSG:XXXX code : %s' %
                        dst_wkt)

    counter = 0
    xres = 0
    yres = 0

    while True:
        feat = lyr.GetNextFeature()
        if feat is None:
            break
        # feat.DumpReadable()

        gdal_ds_name = feat.GetField(tileitem)
        if not os.path.isabs(gdal_ds_name):
            gdal_ds_name = os.path.join(os.path.dirname(ogr_ds_name),
                                        gdal_ds_name)
        gdal_ds = gdal.Open(gdal_ds_name)
        if gdal_ds is None:
            raise Exception('cannot open %s' % gdal_ds_name)
        warped_vrt_ds = gdal.AutoCreateWarpedVRT(gdal_ds, None, dst_wkt)
        if warped_vrt_ds is None:
            raise Exception('cannot warp %s to %s' % (gdal_ds_name, dst_wkt))
        gt = warped_vrt_ds.GetGeoTransform()
        xres += gt[1]
        yres += gt[5]
        warped_vrt_ds = None

        counter = counter + 1

    if counter == 0:
        raise Exception('tileindex is empty')

    xres /= counter
    yres /= counter
    (xmin, xmax, ymin, ymax) = lyr.GetExtent()
    xsize = (int)((xmax - xmin) / xres + 0.5)
    ysize = (int)((ymax - ymin) / abs(yres) + 0.5)

    layername = lyr.GetName()

    if ogr_ds.GetDriver().GetName() != 'ESRI Shapefile':
        print("""LAYER
      NAME "%s_tileindex"
      TYPE POLYGON
      STATUS OFF
      CONNECTIONTYPE OGR
      CONNECTION "%s,%s"
      PROJECTION
        "+init=epsg:%s"
      END
    END""" % (layername, ogr_ds_name, lyr.GetName(), authority_code))
        print("")

        tileindex = "%s_tileindex" % layername
    else:
        tileindex = ogr_ds_name

    print("""LAYER
      NAME "%s"
      TYPE RASTER
      STATUS ON
      TILEINDEX "%s"
      TILEITEM "%s"
      TILESRS "%s"
      PROJECTION
        "+init=epsg:%s"
      END
      METADATA
       "wcs_label"       "%s"
       "wcs_rangeset_name"   "Range 1"  ### required to support DescribeCoverage request
       "wcs_rangeset_label"  "My Label" ### required to support DescribeCoverage request
       "wcs_extent"      "%f %f %f %f"
       "wcs_size"        "%d %d"
       "wcs_resolution"  "%f %f"
      END
    END""" %
          (layername, tileindex, tileitem, tilesrs, authority_code, layername,
           xmin, ymin, xmax, ymax, xsize, ysize, xres, abs(yres)))

    return 0