imio.pyutils 1.0.3__tar.gz → 1.0.4__tar.gz
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-1.0.3 → imio.pyutils-1.0.4}/CHANGES.rst +8 -0
- {imio.pyutils-1.0.3/imio.pyutils.egg-info → imio.pyutils-1.0.4}/PKG-INFO +12 -1
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio/__init__.py +2 -1
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio/pyutils/bs.py +2 -2
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio/pyutils/postgres.py +23 -16
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio/pyutils/system.py +128 -79
- imio.pyutils-1.0.4/imio/pyutils/tests.py +244 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio/pyutils/utils.py +36 -34
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4/imio.pyutils.egg-info}/PKG-INFO +12 -1
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio.pyutils.egg-info/SOURCES.txt +1 -0
- imio.pyutils-1.0.4/imio.pyutils.egg-info/entry_points.txt +3 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio.pyutils.egg-info/requires.txt +2 -1
- imio.pyutils-1.0.4/setup.py +48 -0
- imio.pyutils-1.0.3/imio/pyutils/tests.py +0 -241
- imio.pyutils-1.0.3/setup.py +0 -44
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/MANIFEST.in +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/Makefile +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/README.rst +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio/pyutils/__init__.py +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio.pyutils.egg-info/dependency_links.txt +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio.pyutils.egg-info/namespace_packages.txt +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio.pyutils.egg-info/not-zip-safe +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/imio.pyutils.egg-info/top_level.txt +0 -0
- {imio.pyutils-1.0.3 → imio.pyutils-1.0.4}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: imio.pyutils
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.4
|
|
4
4
|
Summary: Some python useful methods
|
|
5
5
|
Home-page: https://github.com/imio/imio.pyutils/
|
|
6
6
|
Author: IMIO
|
|
@@ -9,6 +9,7 @@ License: GPL
|
|
|
9
9
|
Project-URL: PyPI, https://pypi.python.org/pypi/imio.pyutils
|
|
10
10
|
Project-URL: Source, https://github.com/imio/imio.pyutils
|
|
11
11
|
Keywords: Python IMIO
|
|
12
|
+
Platform: UNKNOWN
|
|
12
13
|
Classifier: Development Status :: 5 - Production/Stable
|
|
13
14
|
Classifier: License :: OSI Approved :: GNU General Public License (GPL)
|
|
14
15
|
Classifier: Operating System :: OS Independent
|
|
@@ -79,6 +80,14 @@ Can be run with: `bin/python -m unittest discover`
|
|
|
79
80
|
Changelog
|
|
80
81
|
=========
|
|
81
82
|
|
|
83
|
+
1.0.4 (2024-06-11)
|
|
84
|
+
------------------
|
|
85
|
+
|
|
86
|
+
- Blacked files.
|
|
87
|
+
[sgeulette]
|
|
88
|
+
- Added `system.post_request` to send a POST request.
|
|
89
|
+
[sgeulette]
|
|
90
|
+
|
|
82
91
|
1.0.3 (2024-05-24)
|
|
83
92
|
------------------
|
|
84
93
|
|
|
@@ -348,3 +357,5 @@ Changelog
|
|
|
348
357
|
|
|
349
358
|
- Initial release.
|
|
350
359
|
[sgeulette]
|
|
360
|
+
|
|
361
|
+
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
|
|
2
2
|
try:
|
|
3
|
-
__import__(
|
|
3
|
+
__import__("pkg_resources").declare_namespace(__name__)
|
|
4
4
|
except ImportError:
|
|
5
5
|
from pkgutil import extend_path
|
|
6
|
+
|
|
6
7
|
__path__ = extend_path(__path__, __name__)
|
|
@@ -68,13 +68,13 @@ def remove_comments(element):
|
|
|
68
68
|
|
|
69
69
|
|
|
70
70
|
def remove_elements(element, to_remove=[]):
|
|
71
|
-
"""Removes sub tags and all their content
|
|
71
|
+
"""Removes sub tags and all their content"""
|
|
72
72
|
for tagtr in to_remove:
|
|
73
73
|
for tag in element.find_all(tagtr):
|
|
74
74
|
tag.decompose()
|
|
75
75
|
|
|
76
76
|
|
|
77
|
-
def replace_entire_strings(element, replace=
|
|
77
|
+
def replace_entire_strings(element, replace="\n", by=""):
|
|
78
78
|
"""Replaces an entire string by another value. With default params, removes newlines.
|
|
79
79
|
|
|
80
80
|
:param element: bs item
|
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
#
|
|
7
7
|
|
|
8
8
|
import psycopg2
|
|
9
|
-
from system import error, trace
|
|
9
|
+
from .system import error, trace
|
|
10
10
|
|
|
11
11
|
# ------------------------------------------------------------------------------
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
# dsn="host=localhost port=5432 dbname= user= password="
|
|
15
15
|
def openConnection(dsn):
|
|
16
|
-
"""
|
|
16
|
+
"""open a postgres connection"""
|
|
17
17
|
conn = None
|
|
18
18
|
try:
|
|
19
19
|
conn = psycopg2.connect(dsn)
|
|
@@ -23,11 +23,12 @@ def openConnection(dsn):
|
|
|
23
23
|
raise Exception(msg)
|
|
24
24
|
return conn
|
|
25
25
|
|
|
26
|
+
|
|
26
27
|
# ------------------------------------------------------------------------------
|
|
27
28
|
|
|
28
29
|
|
|
29
30
|
def insertInTable(dsn, table, columns, vals, TRACE=False):
|
|
30
|
-
"""
|
|
31
|
+
"""insert values in a table"""
|
|
31
32
|
conn = openConnection(dsn)
|
|
32
33
|
cursor = conn.cursor()
|
|
33
34
|
req = "insert into %s(%s) values(%s)" % (table, columns, vals)
|
|
@@ -45,16 +46,17 @@ def insertInTable(dsn, table, columns, vals, TRACE=False):
|
|
|
45
46
|
conn.close()
|
|
46
47
|
return True
|
|
47
48
|
|
|
49
|
+
|
|
48
50
|
# ------------------------------------------------------------------------------
|
|
49
51
|
|
|
50
52
|
|
|
51
|
-
def updateTable(dsn, table, updates, condition=
|
|
52
|
-
"""
|
|
53
|
+
def updateTable(dsn, table, updates, condition="", TRACE=False):
|
|
54
|
+
"""update columns in a table"""
|
|
53
55
|
conn = openConnection(dsn)
|
|
54
56
|
cursor = conn.cursor()
|
|
55
57
|
req = "update %s set %s" % (table, updates)
|
|
56
58
|
if condition:
|
|
57
|
-
req +=
|
|
59
|
+
req += " where %s" % condition
|
|
58
60
|
trace(TRACE, "Update: %s" % req)
|
|
59
61
|
try:
|
|
60
62
|
cursor.execute(req)
|
|
@@ -69,11 +71,12 @@ def updateTable(dsn, table, updates, condition='', TRACE=False):
|
|
|
69
71
|
conn.close()
|
|
70
72
|
return True
|
|
71
73
|
|
|
74
|
+
|
|
72
75
|
# ------------------------------------------------------------------------------
|
|
73
76
|
|
|
74
77
|
|
|
75
78
|
def selectWithSQLRequest(dsn, sql, TRACE=False):
|
|
76
|
-
"""
|
|
79
|
+
"""select multiple lines in a table with a complete sql"""
|
|
77
80
|
conn = openConnection(dsn)
|
|
78
81
|
cursor = conn.cursor()
|
|
79
82
|
req = sql
|
|
@@ -90,16 +93,17 @@ def selectWithSQLRequest(dsn, sql, TRACE=False):
|
|
|
90
93
|
conn.close()
|
|
91
94
|
return data
|
|
92
95
|
|
|
96
|
+
|
|
93
97
|
# ------------------------------------------------------------------------------
|
|
94
98
|
|
|
95
99
|
|
|
96
|
-
def selectAllInTable(dsn, table, selection, condition=
|
|
97
|
-
"""
|
|
100
|
+
def selectAllInTable(dsn, table, selection, condition="", TRACE=False):
|
|
101
|
+
"""select multiple lines in a table"""
|
|
98
102
|
conn = openConnection(dsn)
|
|
99
103
|
cursor = conn.cursor()
|
|
100
104
|
req = "select %s from %s" % (selection, table)
|
|
101
105
|
if condition:
|
|
102
|
-
req +=
|
|
106
|
+
req += " where %s" % condition
|
|
103
107
|
trace(TRACE, "Selection: %s" % req)
|
|
104
108
|
try:
|
|
105
109
|
cursor.execute(req)
|
|
@@ -113,16 +117,17 @@ def selectAllInTable(dsn, table, selection, condition='', TRACE=False):
|
|
|
113
117
|
conn.close()
|
|
114
118
|
return data
|
|
115
119
|
|
|
120
|
+
|
|
116
121
|
# ------------------------------------------------------------------------------
|
|
117
122
|
|
|
118
123
|
|
|
119
|
-
def selectOneInTable(dsn, table, selection, condition=
|
|
120
|
-
"""
|
|
124
|
+
def selectOneInTable(dsn, table, selection, condition="", TRACE=False):
|
|
125
|
+
"""select a single line in a table"""
|
|
121
126
|
conn = openConnection(dsn)
|
|
122
127
|
cursor = conn.cursor()
|
|
123
128
|
req = "select %s from %s" % (selection, table)
|
|
124
129
|
if condition:
|
|
125
|
-
req +=
|
|
130
|
+
req += " where %s" % condition
|
|
126
131
|
trace(TRACE, "Selection: %s" % req)
|
|
127
132
|
try:
|
|
128
133
|
cursor.execute(req)
|
|
@@ -136,16 +141,17 @@ def selectOneInTable(dsn, table, selection, condition='', TRACE=False):
|
|
|
136
141
|
conn.close()
|
|
137
142
|
return data
|
|
138
143
|
|
|
144
|
+
|
|
139
145
|
# ------------------------------------------------------------------------------
|
|
140
146
|
|
|
141
147
|
|
|
142
|
-
def deleteTable(dsn, table, condition=
|
|
143
|
-
"""
|
|
148
|
+
def deleteTable(dsn, table, condition="", TRACE=False):
|
|
149
|
+
"""delete a table"""
|
|
144
150
|
conn = openConnection(dsn)
|
|
145
151
|
cursor = conn.cursor()
|
|
146
152
|
req = "delete from %s" % table
|
|
147
153
|
if condition:
|
|
148
|
-
req +=
|
|
154
|
+
req += " where %s" % condition
|
|
149
155
|
trace(TRACE, "Deletion : %s" % req)
|
|
150
156
|
try:
|
|
151
157
|
cursor.execute(req)
|
|
@@ -160,4 +166,5 @@ def deleteTable(dsn, table, condition='', TRACE=False):
|
|
|
160
166
|
conn.close()
|
|
161
167
|
return True
|
|
162
168
|
|
|
169
|
+
|
|
163
170
|
# ------------------------------------------------------------------------------
|
|
@@ -14,6 +14,7 @@ from six.moves import range
|
|
|
14
14
|
import hashlib
|
|
15
15
|
import os
|
|
16
16
|
import re
|
|
17
|
+
import requests
|
|
17
18
|
import sys
|
|
18
19
|
import tempfile
|
|
19
20
|
import time
|
|
@@ -27,15 +28,15 @@ except ImportError:
|
|
|
27
28
|
|
|
28
29
|
|
|
29
30
|
def verbose(msg):
|
|
30
|
-
print(
|
|
31
|
+
print(">> %s" % msg)
|
|
31
32
|
|
|
32
33
|
|
|
33
34
|
def warning(msg):
|
|
34
|
-
print(
|
|
35
|
+
print("?? {}".format(msg))
|
|
35
36
|
|
|
36
37
|
|
|
37
38
|
def error(msg):
|
|
38
|
-
print(
|
|
39
|
+
print("!! {}".format(msg), file=sys.stderr)
|
|
39
40
|
|
|
40
41
|
|
|
41
42
|
def stop(msg, logger=None):
|
|
@@ -51,49 +52,52 @@ def trace(TRACE, msg):
|
|
|
51
52
|
return
|
|
52
53
|
print("TRACE:'{}'".format(msg))
|
|
53
54
|
|
|
55
|
+
|
|
54
56
|
# --- Writing files ---
|
|
55
57
|
|
|
56
58
|
|
|
57
59
|
def write_to(out_files, key, line):
|
|
58
60
|
"""
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
61
|
+
Open output file and write line (adding line feed)
|
|
62
|
+
outfiles param: dic containing this struct :
|
|
63
|
+
{'key': {'file': 'filepath', 'header': 'First line'}}
|
|
62
64
|
"""
|
|
63
|
-
if
|
|
64
|
-
filename = out_files[key][
|
|
65
|
+
if "fh" not in out_files[key]:
|
|
66
|
+
filename = out_files[key]["file"]
|
|
65
67
|
try:
|
|
66
|
-
out_files[key][
|
|
67
|
-
if
|
|
68
|
-
out_files[key][
|
|
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"])
|
|
69
71
|
except IOError as m:
|
|
70
72
|
error("Cannot create '%s' file: %s" % (filename, m))
|
|
71
73
|
return
|
|
72
|
-
out_files[key][
|
|
74
|
+
out_files[key]["fh"].write("%s\n" % line)
|
|
73
75
|
|
|
74
76
|
|
|
75
77
|
def close_outfiles(outfiles):
|
|
76
|
-
"""
|
|
77
|
-
for key in outfiles.keys():
|
|
78
|
-
if
|
|
79
|
-
outfiles[key][
|
|
78
|
+
"""Close the outfiles"""
|
|
79
|
+
for key in list(outfiles.keys()):
|
|
80
|
+
if "fh" in outfiles[key]:
|
|
81
|
+
outfiles[key]["fh"].close()
|
|
82
|
+
|
|
83
|
+
|
|
80
84
|
# verbose("Output file '%s' generated" % outfiles[key]['file'])
|
|
81
85
|
|
|
82
86
|
# --- Reading files ---
|
|
83
87
|
|
|
84
88
|
|
|
85
|
-
def read_file(filename, strip_chars=
|
|
86
|
-
"""
|
|
89
|
+
def read_file(filename, strip_chars="", skip_empty=False, skip_lines=0):
|
|
90
|
+
"""read a file and return lines"""
|
|
87
91
|
lines = []
|
|
88
92
|
try:
|
|
89
|
-
thefile = open(filename,
|
|
93
|
+
thefile = open(filename, "r")
|
|
90
94
|
except IOError:
|
|
91
95
|
error("! Cannot open %s file" % filename)
|
|
92
96
|
return lines
|
|
93
97
|
for i, line in enumerate(thefile.readlines()):
|
|
94
98
|
if skip_lines and i < skip_lines:
|
|
95
99
|
continue
|
|
96
|
-
line = line.strip(
|
|
100
|
+
line = line.strip("\n")
|
|
97
101
|
if strip_chars:
|
|
98
102
|
line = line.strip(strip_chars)
|
|
99
103
|
if skip_empty and not line:
|
|
@@ -103,15 +107,16 @@ def read_file(filename, strip_chars='', skip_empty=False, skip_lines=0):
|
|
|
103
107
|
return lines
|
|
104
108
|
|
|
105
109
|
|
|
106
|
-
def read_csv(filename, strip_chars=
|
|
107
|
-
"""
|
|
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"""
|
|
108
112
|
lines = []
|
|
109
113
|
try:
|
|
110
|
-
thefile = open(filename,
|
|
114
|
+
thefile = open(filename, "r")
|
|
111
115
|
except IOError:
|
|
112
116
|
error("! Cannot open %s file" % filename)
|
|
113
117
|
return lines
|
|
114
118
|
import csv
|
|
119
|
+
|
|
115
120
|
for i, data in enumerate(csv.reader(thefile, **kwargs)):
|
|
116
121
|
if skip_lines and i < skip_lines:
|
|
117
122
|
continue
|
|
@@ -132,30 +137,32 @@ def read_csv(filename, strip_chars='', replace_dq=True, skip_empty=False, skip_l
|
|
|
132
137
|
return lines
|
|
133
138
|
|
|
134
139
|
|
|
135
|
-
def read_dictcsv(
|
|
136
|
-
|
|
137
|
-
|
|
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"""
|
|
138
144
|
rows = []
|
|
139
145
|
import csv
|
|
146
|
+
|
|
140
147
|
with open(filename) as csvfile:
|
|
141
|
-
reader = csv.DictReader(csvfile, fieldnames=fieldnames, restkey=
|
|
148
|
+
reader = csv.DictReader(csvfile, fieldnames=fieldnames, restkey="_rest", restval="__NO_CO_LU_MN__", **kwargs)
|
|
142
149
|
for row in reader:
|
|
143
150
|
if reader.line_num == 1:
|
|
144
|
-
reader.restval = u
|
|
145
|
-
if
|
|
146
|
-
error(u
|
|
147
|
-
return u
|
|
148
|
-
extra_cols = [key for (key, val) in row.items() if val ==
|
|
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__"]
|
|
149
156
|
if extra_cols:
|
|
150
|
-
error(u
|
|
151
|
-
return u
|
|
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), []
|
|
152
159
|
if reader.line_num <= skip_lines:
|
|
153
160
|
continue
|
|
154
161
|
empty = True
|
|
155
162
|
new_row = {}
|
|
156
163
|
if ln_key:
|
|
157
164
|
new_row[ln_key] = reader.line_num
|
|
158
|
-
for key, val in row.items():
|
|
165
|
+
for key, val in list(row.items()):
|
|
159
166
|
if replace_dq:
|
|
160
167
|
val = val.replace('""', '"')
|
|
161
168
|
if strip_chars:
|
|
@@ -166,11 +173,11 @@ def read_dictcsv(filename, fieldnames=[], strip_chars='', replace_dq=True, skip_
|
|
|
166
173
|
if skip_empty and empty:
|
|
167
174
|
continue
|
|
168
175
|
rows.append(new_row)
|
|
169
|
-
return u
|
|
176
|
+
return u"", rows
|
|
170
177
|
|
|
171
178
|
|
|
172
179
|
def read_dir(dirpath, with_path=False, only_folders=False, only_files=False, to_skip=[]):
|
|
173
|
-
"""
|
|
180
|
+
"""Read the dir and return files"""
|
|
174
181
|
files = []
|
|
175
182
|
for filename in os.listdir(dirpath):
|
|
176
183
|
if filename in to_skip:
|
|
@@ -187,7 +194,7 @@ def read_dir(dirpath, with_path=False, only_folders=False, only_files=False, to_
|
|
|
187
194
|
|
|
188
195
|
|
|
189
196
|
def read_recursive_dir(root_dir, rel_dir, with_folder=False, with_full_path=False, exclude_patterns=[]):
|
|
190
|
-
"""
|
|
197
|
+
"""Read the dir and return files"""
|
|
191
198
|
files = []
|
|
192
199
|
full_dir = os.path.join(root_dir, rel_dir)
|
|
193
200
|
for filename in os.listdir(full_dir):
|
|
@@ -201,8 +208,15 @@ def read_recursive_dir(root_dir, rel_dir, with_folder=False, with_full_path=Fals
|
|
|
201
208
|
if cont:
|
|
202
209
|
continue
|
|
203
210
|
if os.path.isdir(fullpath):
|
|
204
|
-
files.extend(
|
|
205
|
-
|
|
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
|
+
)
|
|
206
220
|
if not with_folder:
|
|
207
221
|
continue
|
|
208
222
|
if with_full_path:
|
|
@@ -213,11 +227,11 @@ def read_recursive_dir(root_dir, rel_dir, with_folder=False, with_full_path=Fals
|
|
|
213
227
|
|
|
214
228
|
|
|
215
229
|
def read_dir_filter(dirpath, with_path=False, only_folders=False, extensions=[], patterns=[]):
|
|
216
|
-
"""
|
|
230
|
+
"""Read the dir and return some files"""
|
|
217
231
|
files = []
|
|
218
232
|
for filename in read_dir(dirpath, with_path=with_path, only_folders=only_folders):
|
|
219
233
|
basename, ext = os.path.splitext(filename)
|
|
220
|
-
if ext and ext.startswith(
|
|
234
|
+
if ext and ext.startswith("."):
|
|
221
235
|
ext = ext[1:]
|
|
222
236
|
if extensions and ext not in extensions:
|
|
223
237
|
continue
|
|
@@ -233,35 +247,38 @@ def read_dir_filter(dirpath, with_path=False, only_folders=False, extensions=[],
|
|
|
233
247
|
|
|
234
248
|
|
|
235
249
|
def read_dir_extensions(dirpath, to_skip=[]):
|
|
236
|
-
"""
|
|
250
|
+
"""Read the dir and return extensions"""
|
|
237
251
|
extensions = []
|
|
238
252
|
for filename in read_dir(dirpath):
|
|
239
253
|
if filename in to_skip:
|
|
240
254
|
continue
|
|
241
255
|
basename, ext = os.path.splitext(filename)
|
|
242
|
-
if ext and ext.startswith(
|
|
256
|
+
if ext and ext.startswith("."):
|
|
243
257
|
ext = ext[1:]
|
|
244
258
|
if ext not in extensions:
|
|
245
259
|
extensions.append(ext)
|
|
246
260
|
extensions.sort()
|
|
247
261
|
return extensions
|
|
248
262
|
|
|
263
|
+
|
|
249
264
|
# ------------------------------------------------------------------------------
|
|
250
265
|
|
|
251
266
|
|
|
252
267
|
def runCommand(cmd, outfile=None, append=True):
|
|
253
|
-
"""
|
|
268
|
+
"""run an os command and get back the stdout and stderr outputs"""
|
|
269
|
+
|
|
254
270
|
def get_ret_code(line):
|
|
255
|
-
match = re.match(r
|
|
271
|
+
match = re.match(r"RET_CODE=(\d+)", line)
|
|
256
272
|
if match is None:
|
|
257
273
|
return -1
|
|
258
274
|
else:
|
|
259
275
|
return int(match.group(1))
|
|
276
|
+
|
|
260
277
|
now = datetime.now()
|
|
261
278
|
if outfile:
|
|
262
|
-
fh = open(outfile,
|
|
263
|
-
fh.write("==================== NEW RUN on {} ====================\n".format(now.strftime(
|
|
264
|
-
fh.write("=> Running '%s' at %s\n" % (cmd, now.strftime(
|
|
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")))
|
|
265
282
|
fh.close()
|
|
266
283
|
os.system(cmd + ' >>{0} 2>&1 ;echo "RET_CODE=$?" >> {0}'.format(outfile))
|
|
267
284
|
lines = read_file(outfile)
|
|
@@ -270,25 +287,25 @@ def runCommand(cmd, outfile=None, append=True):
|
|
|
270
287
|
os.system(cmd + ' >_cmd_pv.out 2>_cmd_pv.err ;echo "RET_CODE=$?" >> _cmd_pv.out')
|
|
271
288
|
stdout = stderr = []
|
|
272
289
|
try:
|
|
273
|
-
if os.path.exists(
|
|
274
|
-
ofile = open(
|
|
290
|
+
if os.path.exists("_cmd_pv.out"):
|
|
291
|
+
ofile = open("_cmd_pv.out", "r")
|
|
275
292
|
stdout = ofile.readlines()
|
|
276
293
|
ofile.close()
|
|
277
|
-
os.remove(
|
|
294
|
+
os.remove("_cmd_pv.out")
|
|
278
295
|
else:
|
|
279
|
-
error("File %s does not exist" %
|
|
296
|
+
error("File %s does not exist" % "_cmd_pv.out")
|
|
280
297
|
except IOError:
|
|
281
|
-
error("Cannot open %s file" %
|
|
298
|
+
error("Cannot open %s file" % "_cmd_pv.out")
|
|
282
299
|
try:
|
|
283
|
-
if os.path.exists(
|
|
284
|
-
ifile = open(
|
|
300
|
+
if os.path.exists("_cmd_pv.err"):
|
|
301
|
+
ifile = open("_cmd_pv.err", "r")
|
|
285
302
|
stderr = ifile.readlines()
|
|
286
303
|
ifile.close()
|
|
287
|
-
os.remove(
|
|
304
|
+
os.remove("_cmd_pv.err")
|
|
288
305
|
else:
|
|
289
|
-
error("File %s does not exist" %
|
|
306
|
+
error("File %s does not exist" % "_cmd_pv.err")
|
|
290
307
|
except IOError:
|
|
291
|
-
error("Cannot open %s file" %
|
|
308
|
+
error("Cannot open %s file" % "_cmd_pv.err")
|
|
292
309
|
return stdout, stderr, get_ret_code(stdout.pop())
|
|
293
310
|
|
|
294
311
|
|
|
@@ -298,15 +315,16 @@ def full_path(path, filename):
|
|
|
298
315
|
return os.path.join(path, filename)
|
|
299
316
|
return filename
|
|
300
317
|
|
|
318
|
+
|
|
301
319
|
# --- Dumping and loading data on disk ---
|
|
302
320
|
|
|
303
321
|
|
|
304
322
|
def load_var(infile, var):
|
|
305
323
|
"""
|
|
306
|
-
|
|
324
|
+
load a dictionary or a list from a file
|
|
307
325
|
"""
|
|
308
326
|
if os.path.exists(infile):
|
|
309
|
-
ofile = open(infile,
|
|
327
|
+
ofile = open(infile, "r")
|
|
310
328
|
if isinstance(var, (dict, set)):
|
|
311
329
|
var.update(eval(ofile.read()))
|
|
312
330
|
elif isinstance(var, list):
|
|
@@ -319,9 +337,9 @@ load_dic = load_var
|
|
|
319
337
|
|
|
320
338
|
def dump_var(outfile, var):
|
|
321
339
|
"""
|
|
322
|
-
|
|
340
|
+
dump a dictionary or a list to a file
|
|
323
341
|
"""
|
|
324
|
-
ofile = open(outfile,
|
|
342
|
+
ofile = open(outfile, "w")
|
|
325
343
|
ofile.write(str(var))
|
|
326
344
|
ofile.close()
|
|
327
345
|
|
|
@@ -331,10 +349,10 @@ dump_dic = dump_var
|
|
|
331
349
|
|
|
332
350
|
def load_pickle(infile, var):
|
|
333
351
|
"""
|
|
334
|
-
|
|
352
|
+
load a dictionary, a set or a list from a pickle file
|
|
335
353
|
"""
|
|
336
354
|
if os.path.exists(infile):
|
|
337
|
-
with open(infile,
|
|
355
|
+
with open(infile, "rb") as fh:
|
|
338
356
|
if isinstance(var, (dict, set)):
|
|
339
357
|
var.update(cPickle.load(fh))
|
|
340
358
|
elif isinstance(var, list):
|
|
@@ -343,9 +361,9 @@ def load_pickle(infile, var):
|
|
|
343
361
|
|
|
344
362
|
def dump_pickle(outfile, var):
|
|
345
363
|
"""
|
|
346
|
-
|
|
364
|
+
dump a dictionary, a set or a list to a file
|
|
347
365
|
"""
|
|
348
|
-
with open(outfile,
|
|
366
|
+
with open(outfile, "wb") as fh:
|
|
349
367
|
cPickle.dump(var, fh, -1)
|
|
350
368
|
|
|
351
369
|
|
|
@@ -353,7 +371,7 @@ def dump_pickle(outfile, var):
|
|
|
353
371
|
|
|
354
372
|
|
|
355
373
|
def human_size(nb):
|
|
356
|
-
size_letter = {1:
|
|
374
|
+
size_letter = {1: "k", 2: "M", 3: "G", 4: "T"}
|
|
357
375
|
for x in range(1, 4):
|
|
358
376
|
quot = nb // 1024 ** x
|
|
359
377
|
if quot < 1024:
|
|
@@ -363,11 +381,11 @@ def human_size(nb):
|
|
|
363
381
|
|
|
364
382
|
def disk_size(path, pretty=True):
|
|
365
383
|
"""
|
|
366
|
-
|
|
384
|
+
return disk size of path content
|
|
367
385
|
"""
|
|
368
386
|
cmd = "du -s"
|
|
369
387
|
if pretty:
|
|
370
|
-
cmd +=
|
|
388
|
+
cmd += "h"
|
|
371
389
|
(cmd_out, cmd_err) = runCommand("%s %s" % (cmd, path))
|
|
372
390
|
for line in cmd_out:
|
|
373
391
|
(size, path) = line.strip().split()
|
|
@@ -387,27 +405,28 @@ def create_temporary_file(initial_file, file_name):
|
|
|
387
405
|
with open(temp_filename, "w") as new_temporary_file:
|
|
388
406
|
new_temporary_file.write(initial_file.data)
|
|
389
407
|
return temp_filename
|
|
390
|
-
return
|
|
408
|
+
return ""
|
|
391
409
|
|
|
392
410
|
|
|
393
411
|
def get_git_tag(path, last=False):
|
|
394
412
|
if last: # from all branches
|
|
395
|
-
cmd =
|
|
396
|
-
|
|
413
|
+
cmd = "git --git-dir={0}/.git describe --tags `git --git-dir={0}/.git rev-list --tags " "--max-count=1`".format(
|
|
414
|
+
path
|
|
415
|
+
)
|
|
397
416
|
else: # current branch only
|
|
398
|
-
cmd =
|
|
417
|
+
cmd = "git --git-dir={}/.git describe --tags".format(path)
|
|
399
418
|
(out, err, code) = runCommand(cmd)
|
|
400
419
|
if code or err:
|
|
401
420
|
error("Problem in command '{}': {}".format(cmd, err))
|
|
402
|
-
return
|
|
403
|
-
return out[0].strip(
|
|
421
|
+
return "NO TAG"
|
|
422
|
+
return out[0].strip("\n")
|
|
404
423
|
|
|
405
424
|
|
|
406
425
|
def get_temporary_filename(file_name):
|
|
407
426
|
"""
|
|
408
427
|
Returns the name of a temporary file.
|
|
409
428
|
"""
|
|
410
|
-
temp_filename =
|
|
429
|
+
temp_filename = "%s/%f_%s" % (
|
|
411
430
|
tempfile.gettempdir(),
|
|
412
431
|
time.time(),
|
|
413
432
|
file_name,
|
|
@@ -415,9 +434,32 @@ def get_temporary_filename(file_name):
|
|
|
415
434
|
return temp_filename
|
|
416
435
|
|
|
417
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
|
+
|
|
418
459
|
def process_memory():
|
|
419
460
|
"""Returns current process memory in MB"""
|
|
420
461
|
import psutil
|
|
462
|
+
|
|
421
463
|
process = psutil.Process(os.getpid())
|
|
422
464
|
infos = process.memory_info()
|
|
423
465
|
# possibly infos[0] in some versions
|
|
@@ -434,8 +476,15 @@ def memory():
|
|
|
434
476
|
* cache memory
|
|
435
477
|
"""
|
|
436
478
|
import psutil
|
|
479
|
+
|
|
437
480
|
mem = psutil.virtual_memory()
|
|
438
|
-
return (
|
|
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
|
+
)
|
|
439
488
|
# mem.active/1024**2, mem.inactive/1024**2)
|
|
440
489
|
|
|
441
490
|
|
|
@@ -451,4 +500,4 @@ def hashed_filename(filename, string, max_length=255):
|
|
|
451
500
|
return filename
|
|
452
501
|
hashed = hashlib.sha1(ensure_binary(string)).hexdigest()
|
|
453
502
|
name, ext = os.path.splitext(filename)
|
|
454
|
-
return
|
|
503
|
+
return "{}_{}{}".format(name, hashed[: (max_length - len(filename))], ext)
|