-
Notifications
You must be signed in to change notification settings - Fork 0
/
ogr2ogr.py
1715 lines (1386 loc) · 67.1 KB
/
ogr2ogr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# *****************************************************************************
# $Id: ogr2ogr.py 428d6fbc987332afb0ba6c7b6913390f7386e864 2020-01-17 22:19:28 +0100 Even Rouault $
#
# Project: OpenGIS Simple Features Reference Implementation
# Purpose: Python port of a simple client for translating between formats.
# Author: Even Rouault, <even dot rouault at spatialys.com>
#
# Port from ogr2ogr.cpp whose author is Frank Warmerdam
#
# *****************************************************************************
# Copyright (c) 2010-2013, Even Rouault <even dot rouault at spatialys.com>
# Copyright (c) 1999, Frank Warmerdam
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# **************************************************************************
# Note : this is the most direct port of ogr2ogr.cpp possible
# It could be made much more Python'ish !
import sys
import os
import stat
#os.environ["GDAL_LIBRARY_PATH"] = "/usr/local/gdal/gdal-3.2.2/lib/libgdal.so"
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
ogr.UseExceptions()
###############################################################################
class ScaledProgressObject(object):
def __init__(self, mini, maxi, cbk, cbk_data=None):
self.min = mini
self.max = maxi
self.cbk = cbk
self.cbk_data = cbk_data
###############################################################################
def ScaledProgressFunc(pct, msg, data):
if data.cbk is None:
return True
return data.cbk(data.min + pct * (data.max - data.min), msg, data.cbk_data)
###############################################################################
def EQUAL(a, b):
return a.lower() == b.lower()
###############################################################################
# Redefinition of GDALTermProgress, so that autotest/pyscripts/test_ogr2ogr_py.py
# can check that the progress bar is displayed
nLastTick = -1
def TermProgress(dfComplete, pszMessage, pProgressArg):
# pylint: disable=unused-argument
global nLastTick
nThisTick = int(dfComplete * 40.0)
if nThisTick < 0:
nThisTick = 0
if nThisTick > 40:
nThisTick = 40
# Have we started a new progress run?
if nThisTick < nLastTick and nLastTick >= 39:
nLastTick = -1
if nThisTick <= nLastTick:
return True
while nThisTick > nLastTick:
nLastTick = nLastTick + 1
if (nLastTick % 4) == 0:
sys.stdout.write('%d' % ((nLastTick / 4) * 10))
else:
sys.stdout.write('.')
if nThisTick == 40:
print(" - done.")
else:
sys.stdout.flush()
return True
class TargetLayerInfo(object):
def __init__(self):
self.poDstLayer = None
self.poCT = None
# self.papszTransformOptions = None
self.panMap = None
self.iSrcZField = None
class AssociatedLayers(object):
def __init__(self):
self.poSrcLayer = None
self.psInfo = None
# **********************************************************************
# main()
# **********************************************************************
bSkipFailures = False
nGroupTransactions = 200
bPreserveFID = False
nFIDToFetch = ogr.NullFID
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
GeomOperation = Enum(["NONE", "SEGMENTIZE", "SIMPLIFY_PRESERVE_TOPOLOGY"])
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
bNullifyOutputSRS = False
poSourceSRS = None
pszNewLayerName = None
pszWHERE = None
poSpatialFilter = None
pszSelect = None
papszSelFields = None
pszSQLStatement = None
eGType = -2
bPromoteToMulti = False
eGeomOp = GeomOperation.NONE
dfGeomOpParam = 0
papszFieldTypesToString = []
bDisplayProgress = False
pfnProgress = None
pProgressArg = None
bClipSrc = False
bWrapDateline = 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
bWrapDateline = False
bExplodeCollections = False
pszZField = None
nCoordDim = -1
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], "PROMOTE_TO_MULTI"):
bPromoteToMulti = True
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], "-dim") and iArg < nArgc - 1:
nCoordDim = int(args[iArg + 1])
if nCoordDim != 2 and nCoordDim != 3:
print("-dim %s: value not handled." % 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]
if EQUAL(pszOutputSRSDef, "NULL") or \
EQUAL(pszOutputSRSDef, "NONE"):
pszOutputSRSDef = None
bNullifyOutputSRS = True
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 bPreserveFID and bExplodeCollections:
print("FAILURE: cannot use -preserve_fid and -explodecollections at the same time\n\n")
return Usage()
if bClipSrc and pszClipSrcDS is not None:
poClipSrc = LoadGeometry(pszClipSrcDS, pszClipSrcSQL, pszClipSrcLayer, pszClipSrcWhere)
if poClipSrc is None:
print("FAILURE: cannot load source clip geometry\n")
return Usage()
elif bClipSrc and poClipSrc is None:
if poSpatialFilter is not None:
poClipSrc = poSpatialFilter.Clone()
if poClipSrc is None:
print("FAILURE: -clipsrc must be used with -spat option or a\n" +
"bounding box, WKT string or datasource must be specified\n")
return Usage()
if pszClipDstDS is not None:
poClipDst = LoadGeometry(pszClipDstDS, pszClipDstSQL, pszClipDstLayer, pszClipDstWhere)
if poClipDst is None:
print("FAILURE: cannot load dest clip geometry\n")
return Usage()
# --------------------------------------------------------------------
# Open data source.
# --------------------------------------------------------------------
poDS = ogr.Open(pszDataSource, False)
# --------------------------------------------------------------------
# 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(" -> " + ogr.GetDriver(iDriver).GetName())
return False
# --------------------------------------------------------------------
# Try opening the output datasource as an existing, writable
# --------------------------------------------------------------------
poODS = None
poDriver = None
if bUpdate:
poODS = ogr.Open(pszDestDataSource, True)
if poODS is None:
if bOverwrite or bAppend:
poODS = ogr.Open(pszDestDataSource, False)
if poODS is None:
# the datasource doesn't exist at all
bUpdate = False
else:
poODS.delete()
poODS = None
if bUpdate:
print("FAILURE:\n" +
"Unable to open existing output datasource `%s'." % pszDestDataSource)
return False
elif papszDSCO:
print("WARNING: Datasource creation options ignored since an existing datasource\n" +
" being updated.")
if poODS is not None:
poDriver = poODS.GetDriver()
# --------------------------------------------------------------------
# Find the output driver.
# --------------------------------------------------------------------
if not bUpdate:
poDriver = ogr.GetDriverByName(pszFormat)
if poDriver is None:
print("Unable to find driver `%s'." % pszFormat)
print("The following drivers are available:")
for iDriver in range(ogr.GetDriverCount()):
print(" -> %s" % ogr.GetDriver(iDriver).GetName())
return False
if not poDriver.TestCapability(ogr.ODrCCreateDataSource):
print("%s driver does not support data source creation." % pszFormat)
return False
# --------------------------------------------------------------------
# Special case to improve user experience when translating
# a datasource with multiple layers into a shapefile. If the
# user gives a target datasource with .shp and it does not exist,
# the shapefile driver will try to create a file, but this is not
# appropriate because here we have several layers, so create
# a directory instead.
# --------------------------------------------------------------------
if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
pszSQLStatement is None and \
(len(papszLayers) > 1 or
(not papszLayers and poDS.GetLayerCount() > 1)) and \
pszNewLayerName is None and \
EQUAL(os.path.splitext(pszDestDataSource)[1], ".SHP"):
try:
os.stat(pszDestDataSource)
except OSError:
try:
# decimal 493 = octal 0755. Python 3 needs 0o755, but
# this syntax is only supported by Python >= 2.6
os.mkdir(pszDestDataSource, 493)
except OSError:
print("Failed to create directory %s\n"
"for shapefile datastore.\n" % pszDestDataSource)
return False
# --------------------------------------------------------------------
# Create the output data source.
# --------------------------------------------------------------------
poODS = poDriver.CreateDataSource(pszDestDataSource, options=papszDSCO)
if poODS is None:
print("%s driver failed to create %s" % (pszFormat, pszDestDataSource))
return False
# --------------------------------------------------------------------
# Parse the output SRS definition if possible.
# --------------------------------------------------------------------
if pszOutputSRSDef is not None:
poOutputSRS = osr.SpatialReference()
poOutputSRS.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
if poOutputSRS.SetFromUserInput(pszOutputSRSDef) != 0:
print("Failed to process SRS definition: %s" % pszOutputSRSDef)
return False
# --------------------------------------------------------------------
# Parse the source SRS definition if possible.
# --------------------------------------------------------------------
if pszSourceSRSDef is not None:
poSourceSRS = osr.SpatialReference()
poSourceSRS.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
if poSourceSRS.SetFromUserInput(pszSourceSRSDef) != 0:
print("Failed to process SRS definition: %s" % pszSourceSRSDef)
return False
# --------------------------------------------------------------------
# For OSM file.
# --------------------------------------------------------------------
bSrcIsOSM = poDS.GetDriver() is not None and \
poDS.GetDriver().GetName() == "OSM"
nSrcFileSize = 0
if bSrcIsOSM and poDS.GetName() != "/vsistdin/":
sStat = gdal.VSIStatL(poDS.GetName())
if sStat is not None:
nSrcFileSize = sStat.size
# --------------------------------------------------------------------
# Special case for -sql clause. No source layers required.
# --------------------------------------------------------------------
if pszSQLStatement is not None:
if pszWHERE is not None:
print("-where clause ignored in combination with -sql.")
if papszLayers:
print("layer names ignored in combination with -sql.")
poResultSet = poDS.ExecuteSQL(pszSQLStatement, poSpatialFilter,
None)
if poResultSet is not None:
nCountLayerFeatures = 0
if bDisplayProgress:
if bSrcIsOSM:
pfnProgress = progress_func
pProgressArg = progress_data
elif not poResultSet.TestCapability(ogr.OLCFastFeatureCount):
print("Progress turned off as fast feature count is not available.")
bDisplayProgress = False
else:
nCountLayerFeatures = poResultSet.GetFeatureCount()
pfnProgress = progress_func
pProgressArg = progress_data
# --------------------------------------------------------------------
# Special case to improve user experience when translating into
# single file shapefile and source has only one layer, and that
# the layer name isn't specified
# --------------------------------------------------------------------
if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
pszNewLayerName is None:
try:
mode = os.stat(pszDestDataSource).st_mode
if (mode & stat.S_IFDIR) == 0:
pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0]
except OSError:
pass
psInfo = SetupTargetLayer(poDS,
poResultSet,
poODS,
papszLCO,
pszNewLayerName,
bTransform,
poOutputSRS,
bNullifyOutputSRS,
poSourceSRS,
papszSelFields,
bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite,
papszFieldTypesToString,
bWrapDateline,
bExplodeCollections,
pszZField,
pszWHERE)
poResultSet.ResetReading()
if psInfo is None or not TranslateLayer(psInfo, poDS, poResultSet, poODS,
poOutputSRS, bNullifyOutputSRS,
eGType, bPromoteToMulti, nCoordDim,
eGeomOp, dfGeomOpParam,
nCountLayerFeatures,
poClipSrc, poClipDst,
bExplodeCollections,
nSrcFileSize, None,
pfnProgress, pProgressArg):
print(
"Terminating translation prematurely after failed\n" +
"translation from sql statement.")
return False
poDS.ReleaseResultSet(poResultSet)
# --------------------------------------------------------------------
# Special case for layer interleaving mode.
# --------------------------------------------------------------------
elif bSrcIsOSM and gdal.GetConfigOption("OGR_INTERLEAVED_READING", None) is None:
gdal.SetConfigOption("OGR_INTERLEAVED_READING", "YES")
# if (bSplitListFields)
# {
# fprintf( stderr, "FAILURE: -splitlistfields not supported in this mode\n" );
# exit( 1 );
# }
nSrcLayerCount = poDS.GetLayerCount()
pasAssocLayers = [AssociatedLayers() for _ in range(nSrcLayerCount)]
# --------------------------------------------------------------------
# Special case to improve user experience when translating into
# single file shapefile and source has only one layer, and that
# the layer name isn't specified
# --------------------------------------------------------------------
if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
(len(papszLayers) == 1 or nSrcLayerCount == 1) and pszNewLayerName is None:
try:
mode = os.stat(pszDestDataSource).st_mode
if (mode & stat.S_IFDIR) == 0:
pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0]
except OSError:
pass
if bDisplayProgress and bSrcIsOSM:
pfnProgress = progress_func
pProgressArg = progress_data
# --------------------------------------------------------------------
# If no target layer specified, use all source layers.
# --------------------------------------------------------------------
if not papszLayers:
papszLayers = [None] * nSrcLayerCount
for iLayer in range(nSrcLayerCount):
poLayer = poDS.GetLayer(iLayer)
if poLayer is None:
print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer)
return False
papszLayers[iLayer] = poLayer.GetName()
else:
if bSrcIsOSM:
osInterestLayers = "SET interest_layers ="
for iLayer, papszLayer in enumerate(papszLayers):
if iLayer != 0:
osInterestLayers = osInterestLayers + ","
osInterestLayers = osInterestLayers + papszLayer
poDS.ExecuteSQL(osInterestLayers, None, None)
# --------------------------------------------------------------------
# First pass to set filters and create target layers.
# --------------------------------------------------------------------
for iLayer in range(nSrcLayerCount):
poLayer = poDS.GetLayer(iLayer)
if poLayer is None:
print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer)
return False
pasAssocLayers[iLayer].poSrcLayer = poLayer
if CSLFindString(papszLayers, poLayer.GetName()) >= 0:
if pszWHERE is not None:
if poLayer.SetAttributeFilter(pszWHERE) != 0:
print("FAILURE: SetAttributeFilter(%s) on layer '%s' failed.\n" % (pszWHERE, poLayer.GetName()))
if not bSkipFailures:
return False
if poSpatialFilter is not None:
poLayer.SetSpatialFilter(poSpatialFilter)
psInfo = SetupTargetLayer(poDS,
poLayer,
poODS,
papszLCO,
pszNewLayerName,
bTransform,
poOutputSRS,
bNullifyOutputSRS,
poSourceSRS,
papszSelFields,
bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite,
papszFieldTypesToString,
bWrapDateline,
bExplodeCollections,
pszZField,
pszWHERE)
if psInfo is None and not bSkipFailures:
return False
pasAssocLayers[iLayer].psInfo = psInfo
else:
pasAssocLayers[iLayer].psInfo = None
# --------------------------------------------------------------------
# Second pass to process features in a interleaved layer mode.
# --------------------------------------------------------------------
bHasLayersNonEmpty = True
while bHasLayersNonEmpty:
bHasLayersNonEmpty = False
for iLayer in range(nSrcLayerCount):
poLayer = pasAssocLayers[iLayer].poSrcLayer
psInfo = pasAssocLayers[iLayer].psInfo
anReadFeatureCount = [0]
if psInfo is not None:
if not TranslateLayer(psInfo, poDS, poLayer, poODS,
poOutputSRS, bNullifyOutputSRS,
eGType, bPromoteToMulti, nCoordDim,
eGeomOp, dfGeomOpParam,
0,
poClipSrc, poClipDst,
bExplodeCollections,
nSrcFileSize,
anReadFeatureCount,
pfnProgress, pProgressArg) \
and not bSkipFailures:
print(
"Terminating translation prematurely after failed\n" +
"translation of layer " + poLayer.GetName() + " (use -skipfailures to skip errors)")
return False
else:
# No matching target layer : just consumes the features
poFeature = poLayer.GetNextFeature()
while poFeature is not None:
anReadFeatureCount[0] = anReadFeatureCount[0] + 1
poFeature = poLayer.GetNextFeature()
if anReadFeatureCount[0] != 0:
bHasLayersNonEmpty = True
else:
nLayerCount = 0
papoLayers = []
# --------------------------------------------------------------------
# Process each data source layer.
# --------------------------------------------------------------------
if not papszLayers:
nLayerCount = poDS.GetLayerCount()
papoLayers = [None] * nLayerCount
iLayer = 0
for iLayer in range(nLayerCount):
poLayer = poDS.GetLayer(iLayer)
if poLayer is None:
print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer)
return False
papoLayers[iLayer] = poLayer
iLayer = iLayer + 1
# --------------------------------------------------------------------
# Process specified data source layers.
# --------------------------------------------------------------------
else:
nLayerCount = len(papszLayers)
papoLayers = [None] * nLayerCount
iLayer = 0
for layername in papszLayers:
poLayer = poDS.GetLayerByName(layername)
if poLayer is None:
print("FAILURE: Couldn't fetch advertised layer %s!" % layername)
return False
papoLayers[iLayer] = poLayer
iLayer = iLayer + 1
panLayerCountFeatures = [0] * nLayerCount
nCountLayersFeatures = 0
nAccCountFeatures = 0
# First pass to apply filters and count all features if necessary
for iLayer in range(nLayerCount):
poLayer = papoLayers[iLayer]
if pszWHERE is not None:
if poLayer.SetAttributeFilter(pszWHERE) != 0:
print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE)
if not bSkipFailures:
return False
if poSpatialFilter is not None:
poLayer.SetSpatialFilter(poSpatialFilter)
if bDisplayProgress and not bSrcIsOSM:
if not poLayer.TestCapability(ogr.OLCFastFeatureCount):
print("Progress turned off as fast feature count is not available.")
bDisplayProgress = False
else:
panLayerCountFeatures[iLayer] = poLayer.GetFeatureCount()
nCountLayersFeatures += panLayerCountFeatures[iLayer]
# Second pass to do the real job
for iLayer in range(nLayerCount):
poLayer = papoLayers[iLayer]
if bDisplayProgress:
if bSrcIsOSM:
pfnProgress = progress_func
pProgressArg = progress_data
else:
pfnProgress = ScaledProgressFunc
pProgressArg = ScaledProgressObject(
nAccCountFeatures * 1.0 / nCountLayersFeatures,
(nAccCountFeatures + panLayerCountFeatures[iLayer]) * 1.0 / nCountLayersFeatures,
progress_func, progress_data)
nAccCountFeatures += panLayerCountFeatures[iLayer]
# --------------------------------------------------------------------
# Special case to improve user experience when translating into
# single file shapefile and source has only one layer, and that
# the layer name isn't specified
# --------------------------------------------------------------------
if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \
nLayerCount == 1 and pszNewLayerName is None:
try:
mode = os.stat(pszDestDataSource).st_mode
if (mode & stat.S_IFDIR) == 0:
pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0]
except OSError:
pass
psInfo = SetupTargetLayer(poDS,
poLayer,
poODS,
papszLCO,
pszNewLayerName,
bTransform,
poOutputSRS,