-
Notifications
You must be signed in to change notification settings - Fork 0
/
_session.py
186 lines (157 loc) · 5.42 KB
/
_session.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
# -*- coding: utf-8 -*-
"""
_session.py -- ArcHacks Table Tools
Author: Garin Wally
License: MIT
These functions/classes are only for use within an ArcMap session though the
Python Window.
"""
import os
import re
import arcpy
import pythonaddins
from _core import fc2fc, TOC, is_active, MXD
# =============================================================================
# GLOBALS
if is_active():
MXD = arcpy.mapping.MapDocument("CURRENT")
else:
MXD = None
def env_switch(env="in_memory"):
arcpy.env.workspace = env
return
def refresh():
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
return
def add_all(source):
"""Adds all contents from a source geodatabase."""
if ".gdb" not in source:
raise AttributeError("Can only accept GDB workspaces")
for workspaces, dfs, contents in arcpy.da.Walk(source):
for content in contents:
lyr_path = "{}\\{}".format(workspaces, content)
try:
lyr = arcpy.mapping.Layer(lyr_path)
arcpy.mapping.AddLayer(TOC.dataframes[0], lyr)
except ValueError:
lyr = arcpy.mapping.TableView(lyr_path)
arcpy.mapping.AddTableView(TOC.dataframes[0], lyr)
refresh()
return
def export_selected_lyr(out_path, where=None, limit_fields=None):
"""Shortcut for exporting the feature class selected in the TOC."""
fc = pythonaddins.GetSelectedTOCLayerOrDataFrame()
fc2fc(fc, out_path, where, limit_fields)
return
# TODO: test
def apply_symbology(in_fc, src_symbology, hide_old=True):
refresh()
arcpy.ApplySymbologyFromLayer_management(in_fc, src_symbology)
if hide_old:
lyr = [f for f in TOC.contents.values() if f.name == src_symbology][0]
lyr.visible = False
refresh()
return
def remove_lyr(rm_lyr):
"""Wrapper for arcpy.mapping.RemoveLayer()."""
for df in TOC.dataframes:
try:
arcpy.mapping.RemoveLayer(df, TOC.contents[rm_lyr])
except:
pass
return
'''
def remove(self):
"""Wrapper for arcpy.mapping.RemoveLayer()."""
for df in TOC.dataframes:
try:
arcpy.mapping.RemoveLayer(df, TOC[self.name])
except:
pass
return
'''
'''
def join_all(fc, uid, to_field=None):
"""Attempts to join a feature class with every table in the TOC."""
if arcpy.Describe(fc).path != "in_memory":
raise IOError("Cannot permanently join data out of 'in_memory'")
if not to_field:
to_field = uid
TOC.refresh()
all_tbls = [lyr for lyr in TOC.values()
if type(lyr).__name__ == "TableView"]
warnings = []
for tbl in all_tbls:
fields = [f.name for f in arcpy.Describe(tbl).fields
if f.name != uid]
try:
arcpy.JoinField_management(fc, uid, tbl, to_field, fields)
except:
warnings.append(tbl.name)
if warnings:
print("Could not join with: {}".format(warnings))
return
'''
'''
class MemoryWorkspace(object):
"""MemoryWorkspace; not to be used in scripts."""
def __init__(self):
self.path = "in_memory"
arcpy.env.workspace = self.path
# def dump(self):
# """Saves workspace to disk."""
@property
def layers(self):
return arcpy.ListFeatureClasses()
def add_layer(self, fc, rename=None, limit_fields=None, hide_old=True):
prefix = "mem_{}"
fc_name = os.path.basename(fc).split(".")[0]
if rename:
out_name = prefix.format(rename)
else:
name = arcpy.Describe(fc).name
if len(re.findall("\.", name)) > 1:
name = name.split(".")[-1]
out_name = prefix.format(name)
fc2fc(fc, "/".join([self.path, out_name]), limit_fields)
# Try to stylize new layer after the non-memory layer's symbology
if fc in TOC.contents.keys():
apply_symbology(out_name, fc_name, hide_old)
return
def add_table(self, tbl, rename=None):
prefix = "mem_{}"
if rename:
out_name = prefix.format(rename)
else:
name = arcpy.Describe(tbl).name
if len(re.findall("\.", name)) > 1:
name = name.split(".")[-1]
out_name = prefix.format(name)
arcpy.TableToTable_conversion(tbl, "in_memory", out_name)
return
def remove(self, fc):
pass
def join_all(self, fc, uid, to_field=None):
"""Attempts to join a feature class with every table in the TOC."""
if arcpy.Describe(fc).path != "in_memory":
raise IOError("Cannot permanently join data out of 'in_memory'")
if not to_field:
to_field = uid
refresh()
all_tbls = [lyr for lyr in TOC.contents.values()
if type(lyr).__name__ == "TableView"]
warnings = []
for tbl in all_tbls:
fields = [f.name for f in arcpy.Describe(tbl).fields
if f.name != uid]
try:
arcpy.JoinField_management(fc, uid, tbl, to_field, fields)
except:
warnings.append(tbl.name)
if warnings:
print("Could not join with: {}".format(warnings))
return
'''
#arcpy._mapping.Layer.join = types.MethodType(func, arcpy._mapping.Layer)
#archacks.TOC.contents["mem_Parcels"].join("ParcelID", "StateGeo", "mem_View_Key")