imio.pyutils 1.1.1__py2.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.
imio/pyutils/system.py ADDED
@@ -0,0 +1,503 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ #
4
+ # system utilities methods
5
+ # IMIO <support@imio.be>
6
+ #
7
+ from __future__ import print_function
8
+
9
+ from datetime import datetime
10
+ from six import ensure_binary
11
+ from six.moves import cPickle
12
+ from six.moves import range
13
+
14
+ import hashlib
15
+ import os
16
+ import re
17
+ import requests
18
+ import sys
19
+ import tempfile
20
+ import time
21
+
22
+
23
+ # can be used in load_var
24
+ try:
25
+ from collections import OrderedDict
26
+ except ImportError:
27
+ from ordereddict import OrderedDict # noqa
28
+
29
+
30
+ def verbose(msg):
31
+ print(">> %s" % msg)
32
+
33
+
34
+ def warning(msg):
35
+ print("?? {}".format(msg))
36
+
37
+
38
+ def error(msg):
39
+ print("!! {}".format(msg), file=sys.stderr)
40
+
41
+
42
+ def stop(msg, logger=None):
43
+ if logger:
44
+ logger.error(msg)
45
+ else:
46
+ error(msg)
47
+ sys.exit(1)
48
+
49
+
50
+ def trace(TRACE, msg):
51
+ if not TRACE:
52
+ return
53
+ print("TRACE:'{}'".format(msg))
54
+
55
+
56
+ # --- Writing files ---
57
+
58
+
59
+ def write_to(out_files, key, line):
60
+ """
61
+ Open output file and write line (adding line feed)
62
+ outfiles param: dic containing this struct :
63
+ {'key': {'file': 'filepath', 'header': 'First line'}}
64
+ """
65
+ if "fh" not in out_files[key]:
66
+ filename = out_files[key]["file"]
67
+ try:
68
+ out_files[key]["fh"] = open(filename, "w")
69
+ if "header" in out_files[key] and out_files[key]["header"]:
70
+ out_files[key]["fh"].write("%s\n" % out_files[key]["header"])
71
+ except IOError as m:
72
+ error("Cannot create '%s' file: %s" % (filename, m))
73
+ return
74
+ out_files[key]["fh"].write("%s\n" % line)
75
+
76
+
77
+ def close_outfiles(outfiles):
78
+ """Close the outfiles"""
79
+ for key in list(outfiles.keys()):
80
+ if "fh" in outfiles[key]:
81
+ outfiles[key]["fh"].close()
82
+
83
+
84
+ # verbose("Output file '%s' generated" % outfiles[key]['file'])
85
+
86
+ # --- Reading files ---
87
+
88
+
89
+ def read_file(filename, strip_chars="", skip_empty=False, skip_lines=0):
90
+ """read a file and return lines"""
91
+ lines = []
92
+ try:
93
+ thefile = open(filename, "r")
94
+ except IOError:
95
+ error("! Cannot open %s file" % filename)
96
+ return lines
97
+ for i, line in enumerate(thefile.readlines()):
98
+ if skip_lines and i < skip_lines:
99
+ continue
100
+ line = line.strip("\n")
101
+ if strip_chars:
102
+ line = line.strip(strip_chars)
103
+ if skip_empty and not line:
104
+ continue
105
+ lines.append(line)
106
+ thefile.close()
107
+ return lines
108
+
109
+
110
+ def read_csv(filename, strip_chars="", replace_dq=True, skip_empty=False, skip_lines=0, **kwargs):
111
+ """read a csv file and return lines"""
112
+ lines = []
113
+ try:
114
+ thefile = open(filename, "r")
115
+ except IOError:
116
+ error("! Cannot open %s file" % filename)
117
+ return lines
118
+ import csv
119
+
120
+ for i, data in enumerate(csv.reader(thefile, **kwargs)):
121
+ if skip_lines and i < skip_lines:
122
+ continue
123
+ replaced = []
124
+ empty = True
125
+ for item in data:
126
+ if replace_dq:
127
+ item = item.replace('""', '"')
128
+ if strip_chars:
129
+ item = item.strip(strip_chars)
130
+ if item:
131
+ empty = False
132
+ replaced.append(item)
133
+ if skip_empty and empty:
134
+ continue
135
+ lines.append(replaced)
136
+ thefile.close()
137
+ return lines
138
+
139
+
140
+ def read_dictcsv(
141
+ filename, fieldnames=[], strip_chars="", replace_dq=True, skip_empty=False, skip_lines=0, ln_key="_ln", **kwargs
142
+ ):
143
+ """read a csv file and return dict row list"""
144
+ rows = []
145
+ import csv
146
+
147
+ with open(filename) as csvfile:
148
+ reader = csv.DictReader(csvfile, fieldnames=fieldnames, restkey="_rest", restval="__NO_CO_LU_MN__", **kwargs)
149
+ for row in reader:
150
+ if reader.line_num == 1:
151
+ reader.restval = u""
152
+ if "_rest" in row:
153
+ error(u"! STOPPING: some columns are not defined in fieldnames: {}".format(row["_rest"]))
154
+ return u"STOPPING: some columns are not defined in fieldnames: {}".format(row["_rest"]), []
155
+ extra_cols = [key for (key, val) in list(row.items()) if val == "__NO_CO_LU_MN__"]
156
+ if extra_cols:
157
+ error(u"! STOPPING: to much columns defined in fieldnames: {}".format(extra_cols))
158
+ return u"STOPPING: to much columns defined in fieldnames: {}".format(extra_cols), []
159
+ if reader.line_num <= skip_lines:
160
+ continue
161
+ empty = True
162
+ new_row = {}
163
+ if ln_key:
164
+ new_row[ln_key] = reader.line_num
165
+ for key, val in list(row.items()):
166
+ if replace_dq:
167
+ val = val.replace('""', '"')
168
+ if strip_chars:
169
+ val = val.strip(strip_chars)
170
+ if val:
171
+ empty = False
172
+ new_row[key] = val
173
+ if skip_empty and empty:
174
+ continue
175
+ rows.append(new_row)
176
+ return u"", rows
177
+
178
+
179
+ def read_dir(dirpath, with_path=False, only_folders=False, only_files=False, to_skip=[]):
180
+ """Read the dir and return files"""
181
+ files = []
182
+ for filename in os.listdir(dirpath):
183
+ if filename in to_skip:
184
+ continue
185
+ if only_folders and not os.path.isdir(os.path.join(dirpath, filename)):
186
+ continue
187
+ if only_files and not os.path.isfile(os.path.join(dirpath, filename)):
188
+ continue
189
+ if with_path:
190
+ files.append(os.path.join(dirpath, filename))
191
+ else:
192
+ files.append(filename)
193
+ return files
194
+
195
+
196
+ def read_recursive_dir(root_dir, rel_dir, with_folder=False, with_full_path=False, exclude_patterns=[]):
197
+ """Read the dir and return files"""
198
+ files = []
199
+ full_dir = os.path.join(root_dir, rel_dir)
200
+ for filename in os.listdir(full_dir):
201
+ fullpath = os.path.join(full_dir, filename)
202
+ relpath = os.path.join(rel_dir, filename)
203
+ cont = False
204
+ for pat in exclude_patterns:
205
+ if re.search(pat, relpath):
206
+ cont = True
207
+ break
208
+ if cont:
209
+ continue
210
+ if os.path.isdir(fullpath):
211
+ files.extend(
212
+ read_recursive_dir(
213
+ root_dir,
214
+ relpath,
215
+ with_folder=with_folder,
216
+ with_full_path=with_full_path,
217
+ exclude_patterns=exclude_patterns,
218
+ )
219
+ )
220
+ if not with_folder:
221
+ continue
222
+ if with_full_path:
223
+ files.append(fullpath)
224
+ else:
225
+ files.append(relpath)
226
+ return files
227
+
228
+
229
+ def read_dir_filter(dirpath, with_path=False, only_folders=False, extensions=[], patterns=[]):
230
+ """Read the dir and return some files"""
231
+ files = []
232
+ for filename in read_dir(dirpath, with_path=with_path, only_folders=only_folders):
233
+ basename, ext = os.path.splitext(filename)
234
+ if ext and ext.startswith("."):
235
+ ext = ext[1:]
236
+ if extensions and ext not in extensions:
237
+ continue
238
+ for pat in patterns:
239
+ if re.search(pat, filename):
240
+ keep = True
241
+ break
242
+ else: # if no break or no patterns
243
+ keep = not patterns and True or False
244
+ if keep:
245
+ files.append(filename)
246
+ return files
247
+
248
+
249
+ def read_dir_extensions(dirpath, to_skip=[]):
250
+ """Read the dir and return extensions"""
251
+ extensions = []
252
+ for filename in read_dir(dirpath):
253
+ if filename in to_skip:
254
+ continue
255
+ basename, ext = os.path.splitext(filename)
256
+ if ext and ext.startswith("."):
257
+ ext = ext[1:]
258
+ if ext not in extensions:
259
+ extensions.append(ext)
260
+ extensions.sort()
261
+ return extensions
262
+
263
+
264
+ # ------------------------------------------------------------------------------
265
+
266
+
267
+ def runCommand(cmd, outfile=None, append=True):
268
+ """run an os command and get back the stdout and stderr outputs"""
269
+
270
+ def get_ret_code(line):
271
+ match = re.match(r"RET_CODE=(\d+)", line)
272
+ if match is None:
273
+ return -1
274
+ else:
275
+ return int(match.group(1))
276
+
277
+ now = datetime.now()
278
+ if outfile:
279
+ fh = open(outfile, "%s" % (append and "a" or "w"))
280
+ fh.write("==================== NEW RUN on {} ====================\n".format(now.strftime("%Y%m%d-%H%M")))
281
+ fh.write("=> Running '%s' at %s\n" % (cmd, now.strftime("%Y%m%d %H:%M")))
282
+ fh.close()
283
+ os.system(cmd + ' >>{0} 2>&1 ;echo "RET_CODE=$?" >> {0}'.format(outfile))
284
+ lines = read_file(outfile)
285
+ return [], [], get_ret_code(lines[-1])
286
+
287
+ os.system(cmd + ' >_cmd_pv.out 2>_cmd_pv.err ;echo "RET_CODE=$?" >> _cmd_pv.out')
288
+ stdout = stderr = []
289
+ try:
290
+ if os.path.exists("_cmd_pv.out"):
291
+ ofile = open("_cmd_pv.out", "r")
292
+ stdout = ofile.readlines()
293
+ ofile.close()
294
+ os.remove("_cmd_pv.out")
295
+ else:
296
+ error("File %s does not exist" % "_cmd_pv.out")
297
+ except IOError:
298
+ error("Cannot open %s file" % "_cmd_pv.out")
299
+ try:
300
+ if os.path.exists("_cmd_pv.err"):
301
+ ifile = open("_cmd_pv.err", "r")
302
+ stderr = ifile.readlines()
303
+ ifile.close()
304
+ os.remove("_cmd_pv.err")
305
+ else:
306
+ error("File %s does not exist" % "_cmd_pv.err")
307
+ except IOError:
308
+ error("Cannot open %s file" % "_cmd_pv.err")
309
+ return stdout, stderr, get_ret_code(stdout.pop())
310
+
311
+
312
+ def full_path(path, filename):
313
+ """Prefixes filename with path if necessary"""
314
+ if not os.path.isabs(filename):
315
+ return os.path.join(path, filename)
316
+ return filename
317
+
318
+
319
+ # --- Dumping and loading data on disk ---
320
+
321
+
322
+ def load_var(infile, var):
323
+ """
324
+ load a dictionary or a list from a file
325
+ """
326
+ if os.path.exists(infile):
327
+ ofile = open(infile, "r")
328
+ if isinstance(var, (dict, set)):
329
+ var.update(eval(ofile.read()))
330
+ elif isinstance(var, list):
331
+ var.extend(eval(ofile.read()))
332
+ ofile.close()
333
+
334
+
335
+ load_dic = load_var
336
+
337
+
338
+ def dump_var(outfile, var):
339
+ """
340
+ dump a dictionary or a list to a file
341
+ """
342
+ ofile = open(outfile, "w")
343
+ ofile.write(str(var))
344
+ ofile.close()
345
+
346
+
347
+ dump_dic = dump_var
348
+
349
+
350
+ def load_pickle(infile, var):
351
+ """
352
+ load a dictionary, a set or a list from a pickle file
353
+ """
354
+ if os.path.exists(infile):
355
+ with open(infile, "rb") as fh:
356
+ if isinstance(var, (dict, set)):
357
+ var.update(cPickle.load(fh))
358
+ elif isinstance(var, list):
359
+ var.extend(cPickle.load(fh))
360
+
361
+
362
+ def dump_pickle(outfile, var):
363
+ """
364
+ dump a dictionary, a set or a list to a file
365
+ """
366
+ with open(outfile, "wb") as fh:
367
+ cPickle.dump(var, fh, -1)
368
+
369
+
370
+ # --- Various ---
371
+
372
+
373
+ def human_size(nb):
374
+ size_letter = {1: "k", 2: "M", 3: "G", 4: "T"}
375
+ for x in range(1, 4):
376
+ quot = nb // 1024 ** x
377
+ if quot < 1024:
378
+ break
379
+ return "%.1f%s" % (float(nb) / 1024 ** x, size_letter[x])
380
+
381
+
382
+ def disk_size(path, pretty=True):
383
+ """
384
+ return disk size of path content
385
+ """
386
+ cmd = "du -s"
387
+ if pretty:
388
+ cmd += "h"
389
+ (cmd_out, cmd_err) = runCommand("%s %s" % (cmd, path))
390
+ for line in cmd_out:
391
+ (size, path) = line.strip().split()
392
+ return size
393
+ return 0
394
+
395
+
396
+ def create_temporary_file(initial_file, file_name):
397
+ """
398
+ Create a temporary copy of a file passed as argument.
399
+ file_name is a string used to create the name of the
400
+ temporary file.
401
+ """
402
+ if initial_file and initial_file.size:
403
+ # save the file in a temporary one
404
+ temp_filename = get_temporary_filename(file_name)
405
+ with open(temp_filename, "w") as new_temporary_file:
406
+ new_temporary_file.write(initial_file.data)
407
+ return temp_filename
408
+ return ""
409
+
410
+
411
+ def get_git_tag(path, last=False):
412
+ if last: # from all branches
413
+ cmd = "git --git-dir={0}/.git describe --tags `git --git-dir={0}/.git rev-list --tags " "--max-count=1`".format(
414
+ path
415
+ )
416
+ else: # current branch only
417
+ cmd = "git --git-dir={}/.git describe --tags".format(path)
418
+ (out, err, code) = runCommand(cmd)
419
+ if code or err:
420
+ error("Problem in command '{}': {}".format(cmd, err))
421
+ return "NO TAG"
422
+ return out[0].strip("\n")
423
+
424
+
425
+ def get_temporary_filename(file_name):
426
+ """
427
+ Returns the name of a temporary file.
428
+ """
429
+ temp_filename = "%s/%f_%s" % (
430
+ tempfile.gettempdir(),
431
+ time.time(),
432
+ file_name,
433
+ )
434
+ return temp_filename
435
+
436
+
437
+ def post_request(url, data=None, json=None, headers=None):
438
+ """Post data to url.
439
+
440
+ :param url: the url to post to
441
+ :param data: a dict to consider
442
+ :param json: a json serializable object
443
+ :param headers: headers to use"""
444
+ kwargs = {
445
+ "headers": headers or {"Content-Type": "application/json"}
446
+ if json
447
+ else {"Content-Type": "application/x-www-form-urlencoded"}
448
+ }
449
+ if json:
450
+ kwargs["json"] = json
451
+ else:
452
+ kwargs["data"] = data
453
+ with requests.post(url, **kwargs) as response:
454
+ if response.status_code != 200:
455
+ error("Error while posting data '%s' to '%s': %s" % (kwargs, url, response.text))
456
+ return response
457
+
458
+
459
+ def process_memory():
460
+ """Returns current process memory in MB"""
461
+ import psutil
462
+
463
+ process = psutil.Process(os.getpid())
464
+ infos = process.memory_info()
465
+ # possibly infos[0] in some versions
466
+ return infos.rss / 1024 ** 2
467
+
468
+
469
+ def memory():
470
+ """Returns memory information in MB.
471
+
472
+ * total memory
473
+ * used memory
474
+ * used memory in percent
475
+ * available memory
476
+ * cache memory
477
+ """
478
+ import psutil
479
+
480
+ mem = psutil.virtual_memory()
481
+ return (
482
+ mem.total / 1024 ** 2,
483
+ mem.used / 1024 ** 2,
484
+ mem.percent,
485
+ mem.available / 1024 ** 2,
486
+ (mem.buffers + mem.cached) / 1024 ** 2,
487
+ )
488
+ # mem.active/1024**2, mem.inactive/1024**2)
489
+
490
+
491
+ def hashed_filename(filename, string, max_length=255):
492
+ """Returns a hashed filename.
493
+
494
+ :param filename: the original filename
495
+ :param string: the string to hash
496
+ :param max_length: the maximum length of the filename
497
+ :return: the hashed filename
498
+ """
499
+ if not string:
500
+ return filename
501
+ hashed = hashlib.sha1(ensure_binary(string)).hexdigest()
502
+ name, ext = os.path.splitext(filename)
503
+ return "{}_{}{}".format(name, hashed[: (max_length - len(filename))], ext)