toolkits 0.2.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- toolkits/3des/3des.py +93 -0
- toolkits/3des/__init__.py +0 -0
- toolkits/__init__.py +2 -0
- toolkits/basic/__init__.py +0 -0
- toolkits/basic/list_helper.py +26 -0
- toolkits/config/__init__.py +0 -0
- toolkits/config/config_demo.py +43 -0
- toolkits/databases/__init__.py +0 -0
- toolkits/databases/database_client_util.py +143 -0
- toolkits/databases/es_client.py +88 -0
- toolkits/databases/hive_client.py +72 -0
- toolkits/databases/hive_cmd.py +113 -0
- toolkits/databases/hive_helper.py +220 -0
- toolkits/databases/redis_mgmt.py +95 -0
- toolkits/databases/sql_helper.py +291 -0
- toolkits/databases/sqlalchemy_helper.py +71 -0
- toolkits/databases/status_check.py +162 -0
- toolkits/db_query_demo.py +72 -0
- toolkits/libs_core/__init__.py +0 -0
- toolkits/libs_core/config_groups_helper.py +60 -0
- toolkits/libs_core/config_helper.py +22 -0
- toolkits/libs_core/env_prepare.py +145 -0
- toolkits/libs_core/load_module.py +46 -0
- toolkits/libs_core/mysql_helper.py +151 -0
- toolkits/network/__init__.py +0 -0
- toolkits/network/ip_helper.py +32 -0
- toolkits/network/pdi_helper.py +206 -0
- toolkits/network/send_mail.py +105 -0
- toolkits/system/__init__.py +0 -0
- toolkits/system/aes_cipher.py +44 -0
- toolkits/system/basic_utils.py +20 -0
- toolkits/system/collections_helper.py +72 -0
- toolkits/system/crpyt_helper.py +39 -0
- toolkits/system/dict2xml.py +416 -0
- toolkits/system/dict_helper.py +29 -0
- toolkits/system/excel_helper.py +101 -0
- toolkits/system/file_helper.py +52 -0
- toolkits/system/load_module.py +47 -0
- toolkits/system/priority_tasks.py +199 -0
- toolkits/system/process_monitor/__init__.py +0 -0
- toolkits/system/process_monitor/process_monitor.py +349 -0
- toolkits/system/shell_helper.py +263 -0
- toolkits/system/str_helper.py +187 -0
- toolkits/system/tasks_deamon/__init__.py +0 -0
- toolkits/system/tasks_deamon/tasks_controller.py +70 -0
- toolkits/system/tasks_deamon/tasks_multiprocessing.py +134 -0
- toolkits/system/tasks_deamon/tasks_process.py +137 -0
- toolkits/system/test_shell_helper.py +2 -0
- toolkits/system/time_helper.py +175 -0
- toolkits/system/win32_env.py +49 -0
- toolkits/tookits_app.py +17 -0
- toolkits/tookits_cli.py +126 -0
- toolkits-0.2.7.dist-info/METADATA +35 -0
- toolkits-0.2.7.dist-info/RECORD +56 -0
- toolkits-0.2.7.dist-info/WHEEL +4 -0
- toolkits-0.2.7.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,416 @@
|
|
1
|
+
#!/usr/bin/env python
|
2
|
+
# coding: utf-8
|
3
|
+
|
4
|
+
"""
|
5
|
+
Converts a Python dictionary or other native data type into a valid XML string.
|
6
|
+
|
7
|
+
Supports item (`int`, `float`, `long`, `decimal.Decimal`, `bool`, `str`, `unicode`, `datetime`, `none` and other number-like objects) and collection (`list`, `set`, `tuple` and `dict`, as well as iterable and dict-like objects) data types, with arbitrary nesting for the collections. Items with a `datetime` type are converted to ISO format strings. Items with a `None` type become empty XML elements.
|
8
|
+
|
9
|
+
This module works with both Python 2 and 3.
|
10
|
+
"""
|
11
|
+
|
12
|
+
|
13
|
+
|
14
|
+
__version__ = '1.7.4'
|
15
|
+
version = __version__
|
16
|
+
|
17
|
+
from random import randint
|
18
|
+
import collections
|
19
|
+
import numbers
|
20
|
+
import logging
|
21
|
+
from xml.dom.minidom import parseString
|
22
|
+
|
23
|
+
|
24
|
+
LOG = logging.getLogger("dicttoxml")
|
25
|
+
expand_list_item_name = True
|
26
|
+
|
27
|
+
# python 3 doesn't have a unicode type
|
28
|
+
try:
|
29
|
+
str
|
30
|
+
except:
|
31
|
+
str = str
|
32
|
+
|
33
|
+
# python 3 doesn't have a long type
|
34
|
+
try:
|
35
|
+
int
|
36
|
+
except:
|
37
|
+
long = int
|
38
|
+
|
39
|
+
|
40
|
+
def set_debug(debug=True, filename='dicttoxml.log'):
|
41
|
+
if debug:
|
42
|
+
import datetime
|
43
|
+
print(('Debug mode is on. Events are logged at: %s' % (filename)))
|
44
|
+
logging.basicConfig(filename=filename, level=logging.INFO)
|
45
|
+
LOG.info('\nLogging session starts: %s' % (
|
46
|
+
str(datetime.datetime.today()))
|
47
|
+
)
|
48
|
+
else:
|
49
|
+
logging.basicConfig(level=logging.WARNING)
|
50
|
+
print('Debug mode is off.')
|
51
|
+
|
52
|
+
|
53
|
+
def unicode_me(something):
|
54
|
+
"""Converts strings with non-ASCII characters to unicode for LOG.
|
55
|
+
Python 3 doesn't have a `unicode()` function, so `unicode()` is an alias
|
56
|
+
for `str()`, but `str()` doesn't take a second argument, hence this kludge.
|
57
|
+
"""
|
58
|
+
try:
|
59
|
+
return str(something, 'utf-8')
|
60
|
+
except:
|
61
|
+
return str(something)
|
62
|
+
|
63
|
+
|
64
|
+
ids = [] # initialize list of unique ids
|
65
|
+
|
66
|
+
def make_id(element, start=100000, end=999999):
|
67
|
+
"""Returns a random integer"""
|
68
|
+
return '%s_%s' % (element, randint(start, end))
|
69
|
+
|
70
|
+
|
71
|
+
def get_unique_id(element):
|
72
|
+
"""Returns a unique id for a given element"""
|
73
|
+
this_id = make_id(element)
|
74
|
+
dup = True
|
75
|
+
while dup:
|
76
|
+
if this_id not in ids:
|
77
|
+
dup = False
|
78
|
+
ids.append(this_id)
|
79
|
+
else:
|
80
|
+
this_id = make_id(element)
|
81
|
+
return ids[-1]
|
82
|
+
|
83
|
+
|
84
|
+
def get_xml_type(val):
|
85
|
+
"""Returns the data type for the xml type attribute"""
|
86
|
+
if type(val).__name__ in ('str', 'unicode'):
|
87
|
+
return 'str'
|
88
|
+
if type(val).__name__ in ('int', 'long'):
|
89
|
+
return 'int'
|
90
|
+
if type(val).__name__ == 'float':
|
91
|
+
return 'float'
|
92
|
+
if type(val).__name__ == 'bool':
|
93
|
+
return 'bool'
|
94
|
+
if isinstance(val, numbers.Number):
|
95
|
+
return 'number'
|
96
|
+
if type(val).__name__ == 'NoneType':
|
97
|
+
return 'null'
|
98
|
+
if isinstance(val, dict):
|
99
|
+
return 'dict'
|
100
|
+
if isinstance(val, collections.Iterable):
|
101
|
+
return 'list'
|
102
|
+
return type(val).__name__
|
103
|
+
|
104
|
+
|
105
|
+
def escape_xml(s):
|
106
|
+
if type(s) in (str, str):
|
107
|
+
s = unicode_me(s) # avoid UnicodeDecodeError
|
108
|
+
s = s.replace('&', '&')
|
109
|
+
s = s.replace('"', '"')
|
110
|
+
s = s.replace('\'', ''')
|
111
|
+
s = s.replace('<', '<')
|
112
|
+
s = s.replace('>', '>')
|
113
|
+
return s
|
114
|
+
|
115
|
+
|
116
|
+
def make_attrstring(attr):
|
117
|
+
"""Returns an attribute string in the form key="val" """
|
118
|
+
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in list(attr.items())])
|
119
|
+
return '%s%s' % (' ' if attrstring != '' else '', attrstring)
|
120
|
+
|
121
|
+
|
122
|
+
def key_is_valid_xml(key):
|
123
|
+
"""Checks that a key is a valid XML name"""
|
124
|
+
LOG.info('Inside key_is_valid_xml(). Testing "%s"' % (unicode_me(key)))
|
125
|
+
test_xml = '<?xml version="1.0" encoding="UTF-8" ?><%s>foo</%s>' % (key, key)
|
126
|
+
try:
|
127
|
+
parseString(test_xml)
|
128
|
+
return True
|
129
|
+
except Exception: # minidom does not implement exceptions well
|
130
|
+
return False
|
131
|
+
|
132
|
+
|
133
|
+
def make_valid_xml_name(key, attr):
|
134
|
+
"""Tests an XML name and fixes it if invalid"""
|
135
|
+
LOG.info('Inside make_valid_xml_name(). Testing key "%s" with attr "%s"' % (
|
136
|
+
unicode_me(key), unicode_me(attr))
|
137
|
+
)
|
138
|
+
key = escape_xml(key)
|
139
|
+
attr = escape_xml(attr)
|
140
|
+
|
141
|
+
# pass through if key is already valid
|
142
|
+
if key_is_valid_xml(key):
|
143
|
+
return key, attr
|
144
|
+
|
145
|
+
# prepend a lowercase n if the key is numeric
|
146
|
+
if key.isdigit():
|
147
|
+
return 'n%s' % (key), attr
|
148
|
+
|
149
|
+
# replace spaces with underscores if that fixes the problem
|
150
|
+
if key_is_valid_xml(key.replace(' ', '_')):
|
151
|
+
return key.replace(' ', '_'), attr
|
152
|
+
|
153
|
+
# key is still invalid - move it into a name attribute
|
154
|
+
attr['name'] = key
|
155
|
+
key = 'key'
|
156
|
+
return key, attr
|
157
|
+
|
158
|
+
|
159
|
+
def wrap_cdata(s):
|
160
|
+
"""Wraps a string into CDATA sections"""
|
161
|
+
s = unicode_me(s).replace(']]>', ']]]]><![CDATA[>')
|
162
|
+
return '<![CDATA[' + s + ']]>'
|
163
|
+
|
164
|
+
|
165
|
+
def default_item_func(parent):
|
166
|
+
return 'item'
|
167
|
+
|
168
|
+
|
169
|
+
def convert(obj, ids, attr_type, item_func, cdata, parent='root'):
|
170
|
+
"""Routes the elements of an object to the right function to convert them
|
171
|
+
based on their data type"""
|
172
|
+
|
173
|
+
LOG.info('Inside convert(). obj type is: "%s", obj="%s"' % (type(obj).__name__, unicode_me(obj)))
|
174
|
+
|
175
|
+
item_name = item_func(parent)
|
176
|
+
|
177
|
+
if isinstance(obj, numbers.Number) or type(obj) in (str, str):
|
178
|
+
return convert_kv(item_name, obj, attr_type, cdata)
|
179
|
+
|
180
|
+
if hasattr(obj, 'isoformat'):
|
181
|
+
return convert_kv(item_name, obj.isoformat(), attr_type, cdata)
|
182
|
+
|
183
|
+
if type(obj) == bool:
|
184
|
+
return convert_bool(item_name, obj, attr_type, cdata)
|
185
|
+
|
186
|
+
if obj is None:
|
187
|
+
return convert_none(item_name, '', attr_type, cdata)
|
188
|
+
|
189
|
+
if isinstance(obj, dict):
|
190
|
+
return convert_dict(obj, ids, parent, attr_type, item_func, cdata)
|
191
|
+
|
192
|
+
if isinstance(obj, collections.Iterable):
|
193
|
+
return convert_list(obj, ids, parent, attr_type, item_func, cdata)
|
194
|
+
|
195
|
+
raise TypeError('Unsupported data type: %s (%s)' % (obj, type(obj).__name__))
|
196
|
+
|
197
|
+
|
198
|
+
def convert_dict(obj, ids, parent, attr_type, item_func, cdata):
|
199
|
+
"""Converts a dict into an XML string."""
|
200
|
+
LOG.info('Inside convert_dict(): obj type is: "%s", obj="%s"' % (
|
201
|
+
type(obj).__name__, unicode_me(obj))
|
202
|
+
)
|
203
|
+
output = []
|
204
|
+
global expand_list_item_name
|
205
|
+
addline = output.append
|
206
|
+
|
207
|
+
item_name = item_func(parent)
|
208
|
+
|
209
|
+
for key, val in list(obj.items()):
|
210
|
+
LOG.info('Looping inside convert_dict(): key="%s", val="%s", type(val)="%s"' % (
|
211
|
+
unicode_me(key), unicode_me(val), type(val).__name__)
|
212
|
+
)
|
213
|
+
|
214
|
+
attr = {} if not ids else {'id': '%s' % (get_unique_id(parent)) }
|
215
|
+
|
216
|
+
key, attr = make_valid_xml_name(key, attr)
|
217
|
+
|
218
|
+
if isinstance(val, numbers.Number) or type(val) in (str, str):
|
219
|
+
addline(convert_kv(key, val, attr_type, attr, cdata))
|
220
|
+
|
221
|
+
elif hasattr(val, 'isoformat'): # datetime
|
222
|
+
addline(convert_kv(key, val.isoformat(), attr_type, attr, cdata))
|
223
|
+
|
224
|
+
elif type(val) == bool:
|
225
|
+
addline(convert_bool(key, val, attr_type, attr, cdata))
|
226
|
+
|
227
|
+
elif isinstance(val, dict):
|
228
|
+
if attr_type:
|
229
|
+
attr['type'] = get_xml_type(val)
|
230
|
+
addline('<%s%s>%s</%s>' % (
|
231
|
+
key, make_attrstring(attr),
|
232
|
+
convert_dict(val, ids, key, attr_type, item_func, cdata),
|
233
|
+
key
|
234
|
+
)
|
235
|
+
)
|
236
|
+
|
237
|
+
elif isinstance(val, collections.Iterable):
|
238
|
+
if attr_type:
|
239
|
+
attr['type'] = get_xml_type(val)
|
240
|
+
if expand_list_item_name:
|
241
|
+
addline('<%s%s>%s</%s>' % (
|
242
|
+
key,
|
243
|
+
make_attrstring(attr),
|
244
|
+
convert_list(val, ids, key, attr_type, item_func, cdata),
|
245
|
+
key
|
246
|
+
)
|
247
|
+
)
|
248
|
+
else:
|
249
|
+
addline('%s' % convert_list(val, ids, key, attr_type, item_func, cdata))
|
250
|
+
|
251
|
+
elif val is None:
|
252
|
+
addline(convert_none(key, val, attr_type, attr, cdata))
|
253
|
+
|
254
|
+
else:
|
255
|
+
raise TypeError('Unsupported data type: %s (%s)' % (
|
256
|
+
val, type(val).__name__)
|
257
|
+
)
|
258
|
+
|
259
|
+
return ''.join(output)
|
260
|
+
|
261
|
+
|
262
|
+
def convert_list(items, ids, parent, attr_type, item_func, cdata):
|
263
|
+
"""Converts a list into an XML string."""
|
264
|
+
LOG.info('Inside convert_list()')
|
265
|
+
global expand_list_item_name
|
266
|
+
output = []
|
267
|
+
addline = output.append
|
268
|
+
|
269
|
+
if expand_list_item_name:
|
270
|
+
item_name = item_func(parent)
|
271
|
+
else:
|
272
|
+
item_name = parent
|
273
|
+
|
274
|
+
if ids:
|
275
|
+
this_id = get_unique_id(parent)
|
276
|
+
|
277
|
+
for i, item in enumerate(items):
|
278
|
+
LOG.info('Looping inside convert_list(): item="%s", item_name="%s", type="%s"' % (
|
279
|
+
unicode_me(item), item_name, type(item).__name__)
|
280
|
+
)
|
281
|
+
attr = {} if not ids else { 'id': '%s_%s' % (this_id, i+1) }
|
282
|
+
if isinstance(item, numbers.Number) or type(item) in (str, str):
|
283
|
+
addline(convert_kv(item_name, item, attr_type, attr, cdata))
|
284
|
+
|
285
|
+
elif hasattr(item, 'isoformat'): # datetime
|
286
|
+
addline(convert_kv(item_name, item.isoformat(), attr_type, attr, cdata))
|
287
|
+
|
288
|
+
elif type(item) == bool:
|
289
|
+
addline(convert_bool(item_name, item, attr_type, attr, cdata))
|
290
|
+
|
291
|
+
elif isinstance(item, dict):
|
292
|
+
if not attr_type:
|
293
|
+
addline('<%s>%s</%s>' % (
|
294
|
+
item_name,
|
295
|
+
convert_dict(item, ids, parent, attr_type, item_func, cdata),
|
296
|
+
item_name,
|
297
|
+
)
|
298
|
+
)
|
299
|
+
else:
|
300
|
+
addline('<%s type="dict">%s</%s>' % (
|
301
|
+
item_name,
|
302
|
+
convert_dict(item, ids, parent, attr_type, item_func, cdata),
|
303
|
+
item_name,
|
304
|
+
)
|
305
|
+
)
|
306
|
+
|
307
|
+
elif isinstance(item, collections.Iterable):
|
308
|
+
if not attr_type:
|
309
|
+
if expand_list_item_name:
|
310
|
+
addline('<%s %s>%s</%s>' % (
|
311
|
+
item_name, make_attrstring(attr),
|
312
|
+
convert_list(item, ids, item_name, attr_type, item_func, cdata),
|
313
|
+
item_name,
|
314
|
+
))
|
315
|
+
else:
|
316
|
+
addline('%s' % convert_list(item, ids, item_name, attr_type, item_func, cdata))
|
317
|
+
else:
|
318
|
+
if expand_list_item_name:
|
319
|
+
addline('<%s type="list"%s>%s</%s>' % (
|
320
|
+
item_name, make_attrstring(attr),
|
321
|
+
convert_list(item, ids, item_name, attr_type, item_func, cdata),
|
322
|
+
item_name,
|
323
|
+
)
|
324
|
+
)
|
325
|
+
else:
|
326
|
+
addline('%s' % convert_list(item, ids, item_name, attr_type, item_func, cdata))
|
327
|
+
|
328
|
+
elif item is None:
|
329
|
+
addline(convert_none(item_name, None, attr_type, attr, cdata))
|
330
|
+
|
331
|
+
else:
|
332
|
+
raise TypeError('Unsupported data type: %s (%s)' % (
|
333
|
+
item, type(item).__name__)
|
334
|
+
)
|
335
|
+
return ''.join(output)
|
336
|
+
|
337
|
+
|
338
|
+
def convert_kv(key, val, attr_type, attr={}, cdata=False):
|
339
|
+
"""Converts a number or string into an XML element"""
|
340
|
+
LOG.info('Inside convert_kv(): key="%s", val="%s", type(val) is: "%s"' % (
|
341
|
+
unicode_me(key), unicode_me(val), type(val).__name__)
|
342
|
+
)
|
343
|
+
|
344
|
+
key, attr = make_valid_xml_name(key, attr)
|
345
|
+
|
346
|
+
if attr_type:
|
347
|
+
attr['type'] = get_xml_type(val)
|
348
|
+
attrstring = make_attrstring(attr)
|
349
|
+
return '<%s%s>%s</%s>' % (
|
350
|
+
key, attrstring,
|
351
|
+
wrap_cdata(val) if cdata == True else escape_xml(val),
|
352
|
+
key
|
353
|
+
)
|
354
|
+
|
355
|
+
|
356
|
+
def convert_bool(key, val, attr_type, attr={}, cdata=False):
|
357
|
+
"""Converts a boolean into an XML element"""
|
358
|
+
LOG.info('Inside convert_bool(): key="%s", val="%s", type(val) is: "%s"' % (
|
359
|
+
unicode_me(key), unicode_me(val), type(val).__name__)
|
360
|
+
)
|
361
|
+
|
362
|
+
key, attr = make_valid_xml_name(key, attr)
|
363
|
+
|
364
|
+
if attr_type:
|
365
|
+
attr['type'] = get_xml_type(val)
|
366
|
+
attrstring = make_attrstring(attr)
|
367
|
+
return '<%s%s>%s</%s>' % (key, attrstring, str(val).lower(), key)
|
368
|
+
|
369
|
+
|
370
|
+
def convert_none(key, val, attr_type, attr={}, cdata=False):
|
371
|
+
"""Converts a null value into an XML element"""
|
372
|
+
LOG.info('Inside convert_none(): key="%s"' % (unicode_me(key)))
|
373
|
+
|
374
|
+
key, attr = make_valid_xml_name(key, attr)
|
375
|
+
|
376
|
+
if attr_type:
|
377
|
+
attr['type'] = get_xml_type(val)
|
378
|
+
attrstring = make_attrstring(attr)
|
379
|
+
return '<%s%s></%s>' % (key, attrstring, key)
|
380
|
+
|
381
|
+
|
382
|
+
def dicttoxml(obj, root=True, custom_root='root', ids=False, attr_type=True,
|
383
|
+
item_func=default_item_func, cdata=False, expand_list_item_name_flag=True):
|
384
|
+
"""Converts a python object into XML.
|
385
|
+
Arguments:
|
386
|
+
- root specifies whether the output is wrapped in an XML root element
|
387
|
+
Default is True
|
388
|
+
- custom_root allows you to specify a custom root element.
|
389
|
+
Default is 'root'
|
390
|
+
- ids specifies whether elements get unique ids.
|
391
|
+
Default is False
|
392
|
+
- attr_type specifies whether elements get a data type attribute.
|
393
|
+
Default is True
|
394
|
+
- item_func specifies what function should generate the element name for
|
395
|
+
items in a list.
|
396
|
+
Default is 'item'
|
397
|
+
- cdata specifies whether string values should be wrapped in CDATA sections.
|
398
|
+
Default is False
|
399
|
+
"""
|
400
|
+
LOG.info('Inside dicttoxml(): type(obj) is: "%s", obj="%s"' % (type(obj).__name__, unicode_me(obj)))
|
401
|
+
global expand_list_item_name
|
402
|
+
expand_list_item_name = expand_list_item_name_flag
|
403
|
+
output = []
|
404
|
+
addline = output.append
|
405
|
+
if root == True:
|
406
|
+
addline('<?xml version="1.0" encoding="UTF-8" ?>')
|
407
|
+
addline('<%s>%s</%s>' % (
|
408
|
+
custom_root,
|
409
|
+
convert(obj, ids, attr_type, item_func, cdata, parent=custom_root),
|
410
|
+
custom_root,
|
411
|
+
)
|
412
|
+
)
|
413
|
+
else:
|
414
|
+
addline(convert(obj, ids, attr_type, item_func, cdata, parent=''))
|
415
|
+
return ''.join(output).encode('utf-8')
|
416
|
+
|
@@ -0,0 +1,29 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
import argparse
|
3
|
+
import sys
|
4
|
+
from log4python.Log4python import log
|
5
|
+
import traceback
|
6
|
+
import importlib
|
7
|
+
importlib.reload(sys)
|
8
|
+
logger = log("MisUserActionEtl")
|
9
|
+
|
10
|
+
|
11
|
+
def set_dict_val(dst_dict, key_list, val):
|
12
|
+
if len(key_list) > 0:
|
13
|
+
key = key_list[0]
|
14
|
+
del key_list[0]
|
15
|
+
dst_dict[key] = set_dict_val(dst_dict[key], key_list, val)
|
16
|
+
return dst_dict
|
17
|
+
else:
|
18
|
+
return val
|
19
|
+
|
20
|
+
|
21
|
+
if __name__ == '__main__':
|
22
|
+
try:
|
23
|
+
parser = argparse.ArgumentParser()
|
24
|
+
parser.add_argument("logFile", type=str, help="specify the log file's path")
|
25
|
+
args = parser.parse_args()
|
26
|
+
print((args.logFile))
|
27
|
+
except Exception as ex:
|
28
|
+
logger.debug("Error: %s" % ex)
|
29
|
+
logger.debug(traceback.format_exc())
|
@@ -0,0 +1,101 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
import argparse
|
3
|
+
import sys
|
4
|
+
|
5
|
+
import unicodecsv
|
6
|
+
from log4python.Log4python import log
|
7
|
+
import traceback
|
8
|
+
import importlib
|
9
|
+
importlib.reload(sys)
|
10
|
+
logger = log("ExcelHelper")
|
11
|
+
|
12
|
+
|
13
|
+
def write_cvs(column_names, rows, csv_file):
|
14
|
+
try:
|
15
|
+
with open(csv_file, 'wb') as f:
|
16
|
+
# w = unicodecsv.writer(f, encoding='utf-8-sig')
|
17
|
+
w = unicodecsv.writer(f, encoding='utf-8')
|
18
|
+
w.writerow(column_names)
|
19
|
+
w.writerows(rows)
|
20
|
+
logger.debug("CsvFile:%s" % csv_file)
|
21
|
+
ret = True
|
22
|
+
except Exception as ex:
|
23
|
+
ret = False
|
24
|
+
logger.error(traceback.format_exc())
|
25
|
+
logger.error('deal_msg error: %s' % ex)
|
26
|
+
return ret
|
27
|
+
|
28
|
+
|
29
|
+
class ExcelHelper:
|
30
|
+
def __init__(self, file_path, column_split=","):
|
31
|
+
self.file_path = file_path
|
32
|
+
self.column_split = column_split
|
33
|
+
self.data = self.load_data()
|
34
|
+
self.cloumns_names = []
|
35
|
+
|
36
|
+
def load_data(self):
|
37
|
+
fp = open(self.file_path)
|
38
|
+
lines = fp.readlines()
|
39
|
+
if len(lines) == 0:
|
40
|
+
return []
|
41
|
+
|
42
|
+
self.cloumns_names = lines[0].strip("\n\r").split(self.column_split)
|
43
|
+
del lines[0] # delete the title
|
44
|
+
|
45
|
+
data = []
|
46
|
+
for item in lines:
|
47
|
+
try:
|
48
|
+
columns_val = item.strip().split(self.column_split)
|
49
|
+
tmp_row = {}
|
50
|
+
for item_index in range(0, len(self.cloumns_names)):
|
51
|
+
if item_index >= len(columns_val):
|
52
|
+
val = ""
|
53
|
+
else:
|
54
|
+
val = columns_val[item_index]
|
55
|
+
tmp_row[self.cloumns_names[item_index]] = val
|
56
|
+
data.append(tmp_row)
|
57
|
+
except Exception as ex:
|
58
|
+
logger.debug("Item:[%s]" % item)
|
59
|
+
logger.error(traceback.format_exc())
|
60
|
+
logger.error('deal_msg error: %s' % ex)
|
61
|
+
return data
|
62
|
+
|
63
|
+
def get_column_data(self, column_name):
|
64
|
+
return self.fetch_column_data(self.data, column_name)
|
65
|
+
|
66
|
+
@staticmethod
|
67
|
+
def fetch_column_data(data, column_name):
|
68
|
+
column_data = []
|
69
|
+
for item in data:
|
70
|
+
column_data.append(item[column_name])
|
71
|
+
return column_data
|
72
|
+
|
73
|
+
@staticmethod
|
74
|
+
def fetch_dict_data(data, key_column_name, val_columns_name):
|
75
|
+
data_dict = {}
|
76
|
+
for item in data:
|
77
|
+
tmp_val = {}
|
78
|
+
for val_name in val_columns_name:
|
79
|
+
tmp_val[val_name] = item[val_name]
|
80
|
+
|
81
|
+
key_name = str(item[key_column_name])
|
82
|
+
if key_name in dict(data_dict):
|
83
|
+
data_dict[key_name].append(tmp_val)
|
84
|
+
else:
|
85
|
+
tmp_list = [tmp_val]
|
86
|
+
data_dict[key_name] = tmp_list
|
87
|
+
|
88
|
+
return data_dict
|
89
|
+
|
90
|
+
def get_dict_data(self, key_column_name, val_columns_name):
|
91
|
+
return self.fetch_dict_data(self.data, key_column_name, val_columns_name)
|
92
|
+
|
93
|
+
if __name__ == '__main__':
|
94
|
+
try:
|
95
|
+
parser = argparse.ArgumentParser()
|
96
|
+
parser.add_argument("excelFile", type=str, help="specify the excel file's path")
|
97
|
+
args = parser.parse_args()
|
98
|
+
csv = ExcelHelper(args.excelFile)
|
99
|
+
except Exception as ex:
|
100
|
+
logger.debug("Error: %s" % ex)
|
101
|
+
logger.debug(traceback.format_exc())
|
@@ -0,0 +1,52 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
import re
|
3
|
+
from os.path import basename
|
4
|
+
from log4python.Log4python import log
|
5
|
+
from unipath import Path
|
6
|
+
logger = log("DirFileSearch")
|
7
|
+
|
8
|
+
|
9
|
+
def read_content(file_path):
|
10
|
+
fp = open(file_path)
|
11
|
+
content = fp.readlines()
|
12
|
+
fp.close()
|
13
|
+
return content
|
14
|
+
|
15
|
+
|
16
|
+
class DirFileSearch:
|
17
|
+
""":cvar
|
18
|
+
file_search = DirFileSearch(".*_1021.log")
|
19
|
+
file_compress_list = file_search.loop_filter_files(target_path)
|
20
|
+
"""
|
21
|
+
def __init__(self, search_pattern):
|
22
|
+
self.__search_pattern = search_pattern
|
23
|
+
|
24
|
+
def __filter_by_name(self, file_path):
|
25
|
+
handle_path = Path(file_path)
|
26
|
+
|
27
|
+
if handle_path.isdir():
|
28
|
+
return file_path
|
29
|
+
|
30
|
+
if handle_path.isfile():
|
31
|
+
file_name = basename(file_path)
|
32
|
+
if re.findall(self.__search_pattern, file_name):
|
33
|
+
return file_path
|
34
|
+
|
35
|
+
def loop_filter_files(self, file_path):
|
36
|
+
file_list = []
|
37
|
+
handle_path = Path(file_path)
|
38
|
+
|
39
|
+
if handle_path.isdir():
|
40
|
+
search_path = file_path
|
41
|
+
loop_next_file_list = Path(search_path).listdir(filter=self.__filter_by_name)
|
42
|
+
for item in loop_next_file_list:
|
43
|
+
tmp_handle_path = Path(item)
|
44
|
+
if tmp_handle_path.isdir():
|
45
|
+
tmp_file_list = self.loop_filter_files(item)
|
46
|
+
file_list.extend(tmp_file_list)
|
47
|
+
else:
|
48
|
+
file_list.append(item)
|
49
|
+
|
50
|
+
if handle_path.isfile():
|
51
|
+
file_list.append(file_path)
|
52
|
+
return file_list
|
@@ -0,0 +1,47 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
import imp
|
3
|
+
import os
|
4
|
+
import sys
|
5
|
+
import traceback
|
6
|
+
import uuid
|
7
|
+
from log4python.Log4python import log
|
8
|
+
import importlib
|
9
|
+
importlib.reload(sys)
|
10
|
+
logger = log("LoadModule")
|
11
|
+
|
12
|
+
|
13
|
+
class LoadModule(object):
|
14
|
+
def __init__(self):
|
15
|
+
pass
|
16
|
+
|
17
|
+
@staticmethod
|
18
|
+
def load_from_file(file_path):
|
19
|
+
mod_name, file_ext = os.path.splitext(os.path.split(file_path)[-1])
|
20
|
+
py_mod = None
|
21
|
+
if file_ext.lower() == '.py':
|
22
|
+
py_mod = imp.load_source(mod_name, file_path)
|
23
|
+
elif file_ext.lower() == '.pyc':
|
24
|
+
py_mod = imp.load_compiled(mod_name, file_path)
|
25
|
+
|
26
|
+
return py_mod
|
27
|
+
|
28
|
+
@staticmethod
|
29
|
+
def __write_tmp_py(file_path, content):
|
30
|
+
fp = open(file_path, "w+")
|
31
|
+
fp.write(content)
|
32
|
+
fp.close()
|
33
|
+
|
34
|
+
def load_from_string(self, func_string, module_name=None):
|
35
|
+
modules = None
|
36
|
+
try:
|
37
|
+
str_random = str(uuid.uuid4()).replace("-", "")
|
38
|
+
if module_name:
|
39
|
+
file_path = "/tmp/dynamic_%s_%s.py" % (module_name, str_random)
|
40
|
+
else:
|
41
|
+
file_path = "/tmp/dynamic_%s.py" % str_random
|
42
|
+
self.__write_tmp_py(file_path, func_string)
|
43
|
+
modules = self.load_from_file(file_path)
|
44
|
+
except Exception as ex:
|
45
|
+
logger.debug("Error: %s" % ex)
|
46
|
+
logger.debug(traceback.format_exc())
|
47
|
+
return modules
|