-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
1239 lines (992 loc) · 39.2 KB
/
common.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
"""helper functions etc"""
from enum import Enum as _Enum
import time as _time
import os as _os
import os.path as _path
import datetime as _datetime
import sys as _sys
import math as _math
from pathlib import Path as _Path
import functools as _functools
import string as _string
import fuckit as _fuckit
import arcpy as _arcpy
import arcproapi.errors as _errors
import funclite.iolib as _iolib
import funclite.stringslib as _stringslib
# Keys is the field type string as a property of arcpy ListFields Field instance
# Values are the type strings used by arcpy AddField
lut_field_types = {
'Date': 'DATE',
'String': 'TEXT',
'Single': 'FLOAT',
'Double': 'DOUBLE',
'SmallInteger': 'SHORT',
'Integer': 'LONG',
'GUID': 'GUID',
'Raster': 'RASTER'
}
class EnumVersion(_Enum):
"""Version enumeration"""
ArcPro = 1
ArcMap = 2
class FieldNamesSpecial:
""" Special field name mappings as text, used in cursors for example
"""
shape = 'SHAPE@'
oid = 'OID@'
wkt = 'SHAPE@WKT'
area = 'SHAPE@AREA'
length = 'SHAPE@LENGTH'
wkb = 'SHAPE@WKB'
json = 'SHAPE@JSON'
m = 'SHAPE@M'
z = 'SHAPE@Z'
x = 'SHAPE@X'
y = 'SHAPE@Y'
true_centroid = 'SHAPE@TRUECENTROID'
xy = 'SHAPE@XY'
xyz = 'SHAPE@XYZ'
# At some point these enumerations should be refactored into enums.py
class EnumFieldTypeText(_Enum):
"""Field Type text as required for addfield..
See also eFieldTypeTextForListFields which is the values
returned by the the type property of an arcpy.Field instance.
Notes:
FLOAT is single precision, DOUBLE is double precision.
Examples:
>>> EnumFieldTypeText.DATE.name
'DATE'
"""
DATE = 1
TEXT = 2
FLOAT = 3
DOUBLE = 4
SHORT = 5
LONG = 6
GUID = 7
RASTER = 8
All = 99
class EnumGeometryType(_Enum):
""" Field type that is used in creating featureclasses etc.
For example:
https://pro.arcgis.com/en/pro-app/latest/tool-reference/data-management/create-feature-class.htm
Examples:
Get text to use in CreateFeatureClass
>>> _arcpy.mananagement.CreateFeatureClass('C:/my.gdb', 'countries', EnumGeometryType.POLYGON.name) # noqa
"""
POINT = 1
MULTIPOINT = 2
POLYGON = 3
POLYLINE = 4
MULTIPATCH = 5
class eFieldTypeTextForListFields(_Enum):
""" These are the field type texts that are passed to arcpy.ListFields
"""
All = 1
BLOB = 2
Date = 3
Double = 4
Geometry = 5
GlobalID = 6
GUID = 7
Integer = 8
OID = 9
Raster = 10
Single = 11
SmallInteger = 12
String = 13
@staticmethod
def as_field_type_text(enum_) -> str:
"""
Get as text used in ESRI AlterField and AddField (i.e. EnumFieldTypeText member name
Args:
enum_: eFieldTypeTextForListFields member or the .name of the eFieldTypeTextForListFields member
Raises:
NotImplemented: If the translation is not supported, e.g. BLOB has no equivalent in EnumFieldTypeText at this time.
Returns:
str: Text to use in ESRI AddField and AlterField
"""
if isinstance(enum_, str):
enum_ = eFieldTypeTextForListFields[enum_]
if enum_ == eFieldTypeTextForListFields.Date:
return EnumFieldTypeText.DATE.name
if enum_ == eFieldTypeTextForListFields.Double:
return EnumFieldTypeText.DOUBLE.name
if enum_ == eFieldTypeTextForListFields.GUID:
return EnumFieldTypeText.GUID.name
if enum_ == eFieldTypeTextForListFields.Integer:
return EnumFieldTypeText.LONG.name
if enum_ == eFieldTypeTextForListFields.SmallInteger:
return EnumFieldTypeText.SHORT.name
if enum_ == eFieldTypeTextForListFields.Single:
return EnumFieldTypeText.FLOAT.name
if enum_ == eFieldTypeTextForListFields.String:
return EnumFieldTypeText.TEXT.name
if enum_ == eFieldTypeTextForListFields.Raster:
return EnumFieldTypeText.RASTER.name
raise NotImplemented('Translation from %s to EnumFieldTypeText not supported' % enum_)
@staticmethod
def as_text(enum_):
"""
Enum name
Returns: str
"""
return enum_.name
def memory_lyr_get(workspace='in_memory') -> str:
""" Just get an 8 char string to use as name for temp layer.
Returns:
str: tmp layer pointer
Examples:
>>> memory_lyr_get()
'in_memory/arehrwfs
"""
return '%s/%s' % (workspace, _stringslib.rndstr(from_=_string.ascii_lowercase))
def tstamp(p="", tf="%Y%m%d%H%M%S", d="_", m=False, s=()):
"""Returns time stamped string.
Return string like p + time in tf + d + s[0] + d + s[1] + d + ... s[n]
If m is True, it will print a message too.
Optional:
p -- prefix
tf -- fime format, default is "%Y%m%d%H%M%S" (i.e. YYYYMMDDHHMMSS)
d -- delimiter between elements of s
s -- tuple or list of postfixes
Example:
>>> tstamp() # '20140216184029'
>>> tstamp("lr") # 'lr20140216184045'
>>> tstamp("lr", "%H%M%S") # 'lr184045'
>>> tstamp("lr", "%H%M%S") # 'lr184045'
>>> tstamp("lr", "%H%M%S", s=('run',1)) # 'lr184527_run_1'
"""
bits = str(d).join(map(str, s))
if bits: bits = d + bits
stamp = str(p) + _time.strftime(tf, _time.localtime()) + bits
if m: msg(stamp, "")
return stamp
def msg(x, timef='%Y-%m-%d %H:%M:%S', verbose=True, log=None, level='message'):
"""Print (and optionally log) a message using print and _arcpy.AddMessage.
In python console, _arcpy.AddMessage does not work but print does.
A message like 'P:2014-02-16 20:44:35: foo' is printed.
In geoprocessing windows, print does not work but _arcpy.AddMessage does,
A message like 'T:2014-02-16 20:44:35: foo' is printed.
In Windows command line, both messages are printed.
_arcpy.AddWarning is used if level is 'warning'
_arcpy.AddError is used if level is 'error', sys.exit() is called then.
If log file does not exist, it is created, otherwise message is appended.
Required:
x -- content of the message
Optional:
timef -- time format, default is "%Y-%m-%d %H:%M:%S" (YYYY-MM-DD HH:MM:SS)
verbose -- if True (default) print the message to the console
log -- file to append the message to, the default is None (i.e. no appending)
level -- one of 'message'|'warning'|'error' or 0|1|2 respectively
Example:
>>> msg('foo') # P:2014-02-16 20:44:35: foo
>>> msg('foo', '%H%M%S') # P:204503: foo
>>> msg('foo', '%H%M%S', True, 'c:\\temp\\log.txt') # P:204531: foo
"""
x = str(x)
level = str(level).lower()
doexit = False
tstamp_ = _time.strftime(timef, _time.localtime())
if verbose:
m = tstamp_ + ": " + x
if level in ('message', '0'):
print("P:" + m)
_arcpy.AddMessage("T:" + m)
elif level in ('warning', '1'):
print("W:" + m)
_arcpy.AddWarning("T:" + m)
elif level in ('error', '2'):
print("E:" + m)
_arcpy.AddError("T:" + m)
doexit = True
else:
em = "Level %s not in 'message'|'warning'|'error'|0|1|2." % level
raise _errors.ArcapiError(em)
if log not in ("", None):
with open(log, "a") as fl:
fl.write("P:" + tstamp_ + ": " + x + "\n")
if doexit:
try:
_sys.exit()
except:
pass
def find(pattern, path, sub_dirs=True):
"""Find files matching a wild card pattern.
Parameters:
pattern -- wild card search (str)
path -- root directory to search
sub_dirs -- search through all sub directories? default is True (bool)
Example:
>>> # find SQL databases (.mdf files)
>>> find('*.mdf', r'\\ArcServer1\SDE')
\\arcserver1\SDE\ALBT\Albertville.mdf
\\arcserver1\SDE\ARLI\Arlington.mdf
\\arcserver1\SDE\BELL\BellePlaine.mdf
\\arcserver1\SDE\BGLK\BigLake.mdf
"""
import fnmatch
the_files = []
for path, dirs, files in _os.walk(path):
for filename in files:
if fnmatch.fnmatch(filename, pattern):
the_files.append(_path.abspath(_path.join(path, filename)))
if sub_dirs in [False, 'false', 0]:
break
return the_files
def fix_args(arg, arg_type=list):
"""Fix arguments from a script tool.
For example, when using a script tool with a multivalue parameter,
it comes in as "val_a;val_b;val_c". This function can automatically
fix arguments based on the arg_type.
Another example is the boolean type returned from a script tool -
instead of True and False, it is returned as "true" and "false".
Required:
arg -- argument from script tool (_arcpy.GetParameterAsText() or sys.argv[1]) (str)
arg_type -- type to convert argument from script tool parameter. Default is list.
Example:
>>> # example of list returned from script tool multiparameter argument
>>> arg = "val_a;val_b;val_c" # noqa
>>> fix_args(arg, list) # noqa
['val_a', 'val_b', 'val_c']
"""
if arg_type == list:
if isinstance(arg, str):
# need to replace extra quotes for paths with spaces
# or anything else that has a space in it
return map(lambda a: a.replace("';'", ";"), arg.split(';'))
else:
return list(arg)
if arg_type == float:
if arg != '#':
return float(arg)
else:
return ''
if arg_type == int:
return int(arg)
if arg_type == bool:
if str(arg).lower() == 'true' or arg == 1:
return True
else:
return False
if arg_type == str:
if arg in [None, '', '#']:
return ''
return arg
def concatenate(vals=(), delimiter='', number_only=False):
"""Concatenate a list of values using a specified delimiter.
Required:
vals -- list of values to concatenate
Optional:
delimiter -- separator for new concatenated string. Default is '' (no delimiter)
number_only -- if True, only numbers in list will be used. Default is False (bool)
"""
if number_only:
return delimiter.join(''.join(str(i) for i in v if str(v).isdigit()) for v in vals)
else:
return delimiter.join(map(str, vals))
def arctype_to_ptype(esri_field_type):
"""(str)->Obj:Type
Convert ArcGIS field type string to Python type.
tp -- ArcGIS type as string like SHORT|LONG|TEXT|DOUBLE|FLOAT...
Returns string for GUID, RASTER, BLOB, or other exotic types.
Example:
>>> arctype_to_ptype("SHORT") # returns int
>>> arctype_to_ptype("long") # returns int
>>> arctype_to_ptype("SmallInteger") # returns int
>>> arctype_to_ptype("DATE") # returns datetime.datetime
"""
esri_field_type = str(esri_field_type).upper().strip()
if esri_field_type == "TEXT" or esri_field_type == "STRING":
return str
elif esri_field_type == "SHORT" or esri_field_type == "SMALLINTEGER":
return int
elif esri_field_type == "LONG" or esri_field_type == "INTEGER":
return int
elif esri_field_type == "DATE" or esri_field_type == "DATETIME":
return _datetime.datetime
elif esri_field_type == "FLOAT" or esri_field_type == "SINGLE":
return float
elif esri_field_type == "DOUBLE":
return float
else:
return str
def list_data(top, **options):
"""Walk down a file structure and pick up all data sets (items).
Returns a generator of full paths to the items.
Uses _arcpy.da.Walk to discover GIS data.
Use the oneach parameter to do something with each item as it is discovered.
Parameters:
top -- full path to the root workspace to start from
Optional keyword arguments:
exclude -- Function that takes item as a parameter and returns True if
the item should be skipped. Default is None, all items are listed.
exclude_dir -- Function that takes the directory name as a parameter and
returns True if the whole directory should be skipped.
Default is None, all directories are listed.
oneach -- Function that takes the item as a parameter.
Default is None and does nothing
onerror -- Function to handle errors, see _arcpy.da.Walk help
datatypes -- list of all data types to discover, see _arcpy.da.Walk help
type -- Feature and raster data types to discover, see _arcpy.da.Walk help
Feature: Multipatch, Multipoint, Point, Polygon, Polyline
Raster: BIL, BIP, BMP, BSQ, DAT, GIF, GRID, IMG, JP2, JPG, PNG, TIF
skippers -- iterable of strings, item is skipped if it contains a skipper
Skippers are not case sensitive
Example:
>>> list_data(r'c:\temp') # noqa
>>> skippers = (".txt", ".xls", ".ttf") # noqa
>>> exclude = lambda a: "_expired2013" in a # noqa
>>> list_data(r'c:\temp', exclude=exclude, skippers=skippers) # noqa
"""
exclude = options.get('exclude', None)
exclude_dir = options.get('exclude_dir', None)
oneach = options.get('oneach', None)
onerror = options.get('onerror', None)
datatypes = options.get('datatypes', None)
type_ = options.get('type', None)
skippers = options.get('skippers', None)
if skippers is not None:
skippers = [str(sk).lower() for sk in skippers]
for dirpath, dirnames, filenames in _arcpy.da.Walk(top, topdown=True, onerror=onerror, followlinks=False, datatype=datatypes, type=type_):
if exclude_dir is not None:
_ = [di for di in dirnames if not exclude_dir(di)]
for filename in filenames:
item = _path.join(dirpath, filename)
if exclude is not None:
# skip items for which exclude is True
if exclude(item):
continue
if skippers is not None:
# skip items that contain any skipper values
if any([item.lower().find(sk) > -1 for sk in skippers]):
continue
if oneach is not None:
# handle item if 'oneach' handler provided
oneach(item)
yield item
def head(tbl: str, n: int = 10, as_rows: bool = True, delimiter: str = "; ", geoms=None, cols: (list, tuple) = ("*",), w: str = "", verbose: bool = True):
"""Return top rows of table tbl.
Returns a list where the first element is a list of tuples representing
first n rows of table tbl, second element is a dictionary like:
{i: {"name":f.name, "values":[1,2,3,4 ...]}} for each field index i.
Args:
tbl (str): The feature class or table
n (int): number of rows to read, default is 10
as_rows (bool): if True (default), columns are printed as rows, otherwise as columns
delimiter (str): string to be used to separate values (if t is True)
geoms: if None (default), print geometries 'as is', else as str(geom).
cols (list, tuple): list of columns to include, include all by default, case insensitive
w (str): where clause to limit selection from tbl
verbose (bool): suppress printing if False, default is True
Example:
>>> tmp = head('c:\\foo\\bar.shp', 5, True, "|", " ")
"""
allcols = ['*', ['*'], ('*',), [], ()]
colslower = [c.lower() for c in cols]
flds = _arcpy.ListFields(_arcpy.Describe(tbl).catalogPath)
if cols not in allcols:
flds = [f for f in flds if f.name.lower() in colslower]
fs = {}
nflds = len(flds)
fieldnames = []
for i in range(nflds):
f = flds[i]
if cols in allcols or f.name in cols:
fieldnames.append(f.name)
fs.update({i: {"name": f.name, "values": []}})
i = 0
hd = []
with _arcpy.da.SearchCursor(tbl, fieldnames, where_clause=w) as sc:
for row in sc:
i += 1
if i > n: break
hd.append(row)
for j in range(nflds):
fs[j]["values"].append(row[j])
if as_rows:
labels = []
values = []
for fld in range(nflds):
f = fs[fld]
fl = flds[fld]
labels.append(str(fl.name) + " (" + str(fl.type) + "," + str(fl.length) + ")")
if fl.type.lower() == 'geometry' and (geoms is not None):
values.append(delimiter.join(map(str, len(f["values"]) * [geoms])))
else:
values.append(delimiter.join(map(str, f["values"])))
longest_label = max(map(len, labels))
for lbl, v in zip(labels, values):
toprint = lbl.ljust(longest_label, ".") + ": " + v
_arcpy.AddMessage(toprint)
if verbose:
print(toprint)
else:
if verbose:
print_tuples(hd, delim=delimiter, tbl=flds, geoms=geoms, returnit=False)
return [hd, fs]
def pretty_now():
return _time.strftime('%H:%M%p %Z on %b %d, %Y')
def editor_tracking_disable(fname: str) -> None:
"""
Disable editor tracking. Won't raise an error if editor tracking for a specific option does not exist (e.g. last editor is not enabled').
All errors are suppressed with fuckit.
See https://pro.arcgis.com/en/pro-app/latest/tool-reference/data-management/disable-editor-tracking.htm
Args:
fname (str): The table/layer
Returns:
None
Examples:
First setting a workspace
>>> import arcpy
>>> arcpy.env.workspace = 'C:/my.gdb'
>>> editor_tracking_disable('MyLayer')
\n\nWithout setting a workspace
>>> editor_tracking_disable('C:/my.gdb/MyLayer')
"""
fname = _path.normpath(fname)
with _fuckit:
_arcpy.management.DisableEditorTracking(fname, creator='DISABLE_CREATOR')
_arcpy.management.DisableEditorTracking(fname, creation_date='DISABLE_CREATION_DATE')
_arcpy.management.DisableEditorTracking(fname, last_editor='DISABLE_LAST_EDITOR')
_arcpy.management.DisableEditorTracking(fname, last_edit_date='DISABLE_LAST_EDIT_DATE')
def print_tuples(x, delim=" ", tbl=None, geoms=None, fillchar=" ", padding=1, verbose=True, returnit=False):
"""Print and/or return list of tuples formatted as a table.
Intended for quick printing of lists of tuples in the terminal.
Returns None or the formatted table depending on value of returnit.
Required:
x -- input list of tuples to print (can be tuple of tuples, list of lists).
Optional:
delim -- delimiter to use between columns
tbl -- table or list of _arcpy.Field objects to take column headings from (default is None)
geoms -- if None (default), print geometries 'as is', else as str(geom).
Works only is valid tbl is specified.
filchar -- string to be used to pad values
padding -- how many extra fillchars to use in cells
verbose -- suppress printing when False, default is True
returnit -- if True, return the formatted table, else return None (default)
"""
lpadding, rpadding = padding, padding
fch = fillchar
# find column widths
gi = None
if tbl is None:
nms = ["V" + str(a) for a in range(len(x[0]))]
tps = ["LONG" if str(ti).isdigit() else "TEXT" for ti in x[0]]
geoms = None
else:
nms, tps = [], []
i = 0
if isinstance(tbl, list) or isinstance(tbl, tuple):
fields = tbl
else:
fields = _arcpy.ListFields(tbl)
for f in fields:
nms.append(f.name)
tps.append(f.type)
if f.type.lower() == "geometry" and geoms is not None:
gi = i # index of geometry column
i += 1
to_left = []
left_types = ("STRING", "TEXT") # field types to be left justified
for nmi in range(len(nms)):
if tps[nmi].upper() in left_types:
to_left.append(nmi)
widths = []
for nmi in range(len(nms)):
widths.append(len(str(nms[nmi])))
for tpl in x:
for nmi in range(len(nms)):
if geoms is not None and nmi == gi:
clen = len(str(geoms))
else:
clen = len(str(tpl[nmi]))
if clen > widths[nmi]:
widths[nmi] = clen
sbuilder = []
frmtd = []
for nmi in range(len(nms)):
pad = widths[nmi] + lpadding + rpadding
frmtd.append(str(nms[nmi]).center(pad, fch))
hdr = delim.join(frmtd)
if verbose: print(hdr) # print header
sbuilder.append(hdr)
for r in x:
frmtd = []
for nmi in range(len(nms)):
if nmi in to_left:
if geoms is not None and nmi == gi:
pad = widths[nmi] + rpadding
padfull = pad + lpadding
valf = str(geoms).ljust(pad, fch).rjust(padfull, fch)
else:
pad = widths[nmi] + rpadding
padfull = pad + lpadding
valf = str(r[nmi]).ljust(pad, fch).rjust(padfull, fch)
else:
if geoms is not None and nmi == gi:
pad = widths[nmi] + lpadding
padfull = pad + rpadding
valf = str(geoms).rjust(pad, fch).ljust(padfull, fch)
else:
pad = widths[nmi] + lpadding
padfull = pad + rpadding
valf = str(r[nmi]).rjust(pad, fch).ljust(padfull, fch)
frmtd.append(valf)
rw = delim.join(frmtd)
if verbose:
print(rw) # print row
sbuilder.append(rw)
ret = "\n".join(sbuilder) if returnit else None
return ret
def nrow(x):
"""Return number of rows in a table as integer.
Required:
x -- input table or table view
Example:
>>> nrow('c:\\foo\\bar.shp')
"""
return int(_arcpy.GetCount_management(x).getOutput(0))
def get_row_count(fname: str) -> int:
"""Return number of rows in a table as integer.
Args:
fname (str): Input table or table view
Notes:
Same as nrow (which it wraps)
Returns:
int: Row count of table/feature class fname
Examples:
>>> get_row_count('c:\\foo\\bar.shp')
12
"""
return nrow(fname)
def get_row_count2(fname: str, where: (str, None) = None) -> int:
"""
Get nr rows using a SearchCursor, allowing use of a where clause
Args:
fname (str): path to feature class/layer
where (str): where SQL string, passed to the searchcursor where_clause
Returns:
int: Row count of table/feature class fname
Examples:
>>> get_row_count2('c:\\foo\\bar.shp', where='OBJECTID>10')
2
"""
n = 0
try:
with _arcpy.da.SearchCursor(fname, ['OID@'], where_clause=where) as Cur:
for _ in Cur:
n += 1
except RuntimeError as e:
if 'field was not found' in str(e):
raise ValueError('Get_row_count2 failed. The where clause "%s" referenced a field that does not exist in %s' % (where, fname))
return n
def is_locked(fname: str) -> (bool, None):
"""
Check of feature class schema is locked
Args:
fname (str): Feature class/table etc.
Returns:
bool: True if schema locked else False
None: fname does not exist
Notes:
This checks for a schema lock, a schema lock does not necessarily
indicate that data could not be added or edited .. but is a
pretty good indication that anything you do with the table is
going to fail ... and that may fail silently.
Examples:
>>> is_locked('C:/my.gdb/mylayer')
False
>>> is_locked('C:/my.gdb/god')
None
"""
fname = _path.normpath(fname)
if not _arcpy.Exists(fname):
return None # noqa
return not _arcpy.TestSchemaLock(fname)
def field_name_clean(s: str, recursions: int = 100):
"""
Cleans a field name to reduce it to a lower case alpha-ASCII name delimited by underscores
Args:
s: the string
recursions: Defensive getout as their is a recursive-like call here
Raises:
RecursionError: If over "recursions" attempts are made to fix seperator character (i.e. "_") duplicates
Returns:
str: The cleaned name. Returns empty string if "not s" evaluates to True
Examples:
>>> field_name_clean('_123my-field')
'my_field'
>>> field_name_clean('123my-8£$field1')
'my_field1'
"""
if not s: return ''
ss = s
ss = ss.replace("'", "")
ss = ss.replace('"', '')
for ltr in _string.punctuation:
ss = ss.replace(ltr, '_')
ss = ss.lower()
ss = _stringslib.filter_alphanumeric1(ss, strict=True, include=('_'))
ss = ss.replace(' ', '_')
n = 0
while True:
if not ss: return ''
i = len(ss)
ss = ss.replace('__', '_')
if i == len(ss): break
n += 1
# Lets not risk getting in infinite recursion - defensive get-out
if n > recursions:
raise RecursionError('Recursion error when fixing input string "%s"' % s)
ss.lstrip('0123456789')
# ss.rstrip('0123456789') # Nope, lets keep these, suffixing with a number is just about valid practice/naming e.g. comment1, comment2
ss = ss.strip('_')
return ss
def names(fname, filterer=None):
"""(str, func)->list
Returns a list of column names of a table.
Parameters:
fname -- input table or table view
filterer -- function, only fields where filterer returns True are listed
Example:
>>> names('c:\\foo\\bar.shp', lambda f: f.name.startswith('eggs')) # noqa
>>> ['eggscellent']
"""
flds = _arcpy.ListFields(fname)
if filterer is None: filterer = lambda a: True
return [f.name for f in flds if filterer(f)]
def get_id_col(fname):
"""get name of objectid/fid column
This will save lots of annoyance as ArcGIS will change the name
of the autoincremental key field dependant on the source type"""
return names(fname)[0]
def columns_delim(cols: (str, list, tuple), fname_or_db: str = '') -> list:
"""
Get a list of properly delimited fields - used to generate where clauses
for example by pypika
Args:
cols (list, str, tuple): string or iterable of column names
fname_or_db (str): fully qualified path to the datasource
Notes:
https://pro.arcgis.com/en/pro-app/latest/arcpy/functions/addfielddelimiters.htm
Defaults to the current workspace if fname_or_db evaluates to false
Examples:
>>> columns_delim(('col_a', 'col_b'), 'c:/geo.gdb')
['"col_a"', '"col_b"']
"""
if not fname_or_db:
fname_or_db = _arcpy.env.workspace
if isinstance(cols, str): cols = (cols,)
return [_arcpy.AddFieldDelimiters(fname_or_db, s) for s in cols]
def is_shp(fname: str) -> bool:
"""Does it look like a shape file
Args:
fname (str): feature class
Returns: bool
Notes:
Currently just checks for .shp at end of fname
TODO:
make is_shape and is_gdb robust
"""
return fname[-4:] == '.shp'
def is_gdb(fname):
"""Does it look like a gdb feature class
Args:
fname (str): feature class
Returns: bool
Notes:
currently just checks for .gdb in fname
"""
return fname[-4:] == '.gdb'
def is_memory(fname):
"""Does it look like a memory feature class
Args:
fname (str): feature class
Returns: bool
Notes:
currently just checks for starting with "memory/" or "in_memory/" in fname
"""
fname = _path.normpath(fname).lower()
if fname[0:len('memory/')] in ('memory/', 'memory\\') : return True
if fname[0:len('in_memory/')] in ('in_memory/', 'in_memory\\'): return True
return False
def gdb_from_fname(fname: str) -> str:
"""
Get gdb path from a full qualified feature class or table path. Returns memory or in_memory if these are the workspace of fname
Args:
fname (str): the full qualified path
Returns:
str: The gdb path. Empty string if ".gdb" not in fname
Notes:
Just looks for gdb and slices the string out accordingly.
Hence will fail if you have a path with multiple occurences of ".gdb"
*** Superseeded by workspace_from_fname which handles any compatible spatial data source ***
Examples:
>>> gdb_from_fname('C:/my.gdb/my/layer')
'C:/my.gdb'
"""
fname = _path.normpath(fname)
if fname[0:6] == 'memory': return 'memory'
if fname[0:9] == 'in_memory': return 'in_memory'
if '.gdb' in fname:
return fname[0:fname.index('.gdb\\') + 4]
return ''
def workspace_from_fname(fname: str, simple_gdb_test: bool = True) -> (str, None):
""" Get the workspace from a given layer/table name.
Also see gdb_from_fname - which this superceeds, but performs quicker for file geodatabases.
Currently supports Enterprise geodatabases and file geodatabases'
Returns memory or in_memory if these are the workspace of fname
Args:
fname (str): The layer or feature class path
simple_gdb_test (bool): Enable calling gdb_from_fname first to try and get the workspace, can save time if know we have a gdb.
Returns:
str: The workspace name
None: If no geodatabase could be discerned from fname
Notes:
Oracle SDE layers are a pain and need fully qualifying with schema names.
Use an instance of arcproapi.connection.OracleSDELayer to ease creation of fully qualified paths for SDE layers.
This attempt to call Describe until it gets a match on known properties for spatial databases. Hence performance will probably be slow.
At some time, ESRI will hopefully implement the database source when Describe-ing a table or feature class
Examples:
>>> workspace_from_fname('C:/my.gdb/my_layer', simple_gdb_test=True)
'C:/my.gdb'
"""
fname = _path.normpath(fname)
parts = _Path(fname).parts
if fname[0:6] == 'memory': return 'memory'
if fname[0:9] == 'in_memory': return 'in_memory'
if simple_gdb_test:
# if we have a gdb, lets just use that and get out of here for performance reasons, but stick in try catch so don't have to think.
ws = None
try:
ws = gdb_from_fname(fname) # returns empty string if fails
except:
pass
if ws: return ws
# TODO Debug/test workspace_from_fname
for i in reversed(range(len(parts))):
root = _iolib.fixp(*parts[0:i])
# Add more try catches for other geodatabases - currently pGDBs and Enterprise Geodbs catered for
try:
D = _arcpy.Describe(root)
try:
if D.connectionproperties.instance:
return root
except:
pass
if D.connectionproperties.database:
return root
except:
pass
return None # noqa
# this is reproduced in stuct, but don'as_rows import as will end up with circular reference issues
def oid_field(fname):
"""(str)->str
Get the primary key field names
Args:
fname (str): path to feature class/table etc.
Returns:
str: Name of the autoincremental primary key field
"""
return _arcpy.Describe(fname).OIDFieldName
# this is reproduced in stuct. Dont refactor or will risk ending up with circular references
def shape_field(fname: str) -> str:
"""
Return name of the Shape (Geometry) field in feature class fname
Args:
fname (str): path to feature class/table etc.
Returns:
str: Name of the shape/geometry field
"""
return _arcpy.Describe(fname).ShapeFieldName