forked from wolph/python-progressbar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
426 lines (347 loc) · 11.8 KB
/
utils.py
File metadata and controls
426 lines (347 loc) · 11.8 KB
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
import io
import os
import sys
import math
import logging
import datetime
import six
# There might be a better way to get the epoch with tzinfo, please create
# a pull request if you know a better way that functions for Python 2 and 3
epoch = datetime.datetime(year=1970, month=1, day=1)
class WrappingIO:
def __init__(self, target, capturing=False):
self.buffer = six.StringIO()
self.target = target
self.capturing = capturing
def write(self, value):
if self.capturing:
self.buffer.write(value)
else:
self.target.write(value)
def flush(self):
self.buffer.flush()
def _flush(self):
value = self.buffer.getvalue()
if value:
self.flush()
self.target.write(value)
self.buffer.seek(0)
self.buffer.truncate(0)
class StreamWrapper(object):
'''Wrap stdout and stderr globally'''
def __init__(self):
self.stdout = self.original_stdout = sys.stdout
self.stderr = self.original_stderr = sys.stderr
self.original_excepthook = sys.excepthook
self.wrapped_stdout = 0
self.wrapped_stderr = 0
self.wrapped_excepthook = 0
self.capturing = 0
if os.environ.get('WRAP_STDOUT'): # pragma: no cover
self.wrap_stdout()
if os.environ.get('WRAP_STDERR'): # pragma: no cover
self.wrap_stderr()
def start_capturing(self):
self.capturing += 1
self.update_capturing()
def stop_capturing(self):
self.capturing -= 1
self.update_capturing()
def update_capturing(self): # pragma: no cover
if isinstance(self.stdout, WrappingIO):
self.stdout.capturing = self.capturing > 0
if isinstance(self.stderr, WrappingIO):
self.stderr.capturing = self.capturing > 0
if self.capturing <= 0:
self.flush()
def wrap(self, stdout=False, stderr=False):
if stdout:
self.wrap_stdout()
if stderr:
self.wrap_stderr()
def wrap_stdout(self):
self.wrap_excepthook()
if not self.wrapped_stdout:
self.stdout = sys.stdout = WrappingIO(self.original_stdout)
self.wrapped_stdout += 1
return sys.stdout
def wrap_stderr(self):
self.wrap_excepthook()
if not self.wrapped_stderr:
self.stderr = sys.stderr = WrappingIO(self.original_stderr)
self.wrapped_stderr += 1
return sys.stderr
def unwrap_excepthook(self):
if self.wrapped_excepthook:
self.wrapped_excepthook -= 1
sys.excepthook = self.original_excepthook
def wrap_excepthook(self):
if not self.wrapped_excepthook:
logger.debug('wrapping excepthook')
self.wrapped_excepthook += 1
sys.excepthook = self.excepthook
def unwrap(self, stdout=False, stderr=False):
if stdout:
self.unwrap_stdout()
if stderr:
self.unwrap_stderr()
def unwrap_stdout(self):
if self.wrapped_stdout > 1:
self.wrapped_stdout -= 1
else:
sys.stdout = self.original_stdout
self.wrapped_stdout = 0
def unwrap_stderr(self):
if self.wrapped_stderr > 1:
self.wrapped_stderr -= 1
else:
sys.stderr = self.original_stderr
self.wrapped_stderr = 0
def flush(self):
if self.wrapped_stdout: # pragma: no branch
try:
self.stdout._flush()
except (io.UnsupportedOperation,
AttributeError): # pragma: no cover
self.wrapped_stdout = False
logger.warn('Disabling stdout redirection, %r is not seekable',
sys.stdout)
if self.wrapped_stderr: # pragma: no branch
try:
self.stderr._flush()
except (io.UnsupportedOperation,
AttributeError): # pragma: no cover
self.wrapped_stderr = False
logger.warn('Disabling stderr redirection, %r is not seekable',
sys.stderr)
def excepthook(self, exc_type, exc_value, exc_traceback):
self.original_excepthook(exc_type, exc_value, exc_traceback)
self.flush()
streams = StreamWrapper()
logger = logging.getLogger(__name__)
def timedelta_to_seconds(delta):
'''Convert a timedelta to seconds with the microseconds as fraction
>>> from datetime import timedelta
>>> '%d' % timedelta_to_seconds(timedelta(days=1))
'86400'
>>> '%d' % timedelta_to_seconds(timedelta(seconds=1))
'1'
>>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1))
'1.000001'
>>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1))
'0.000001'
'''
# Only convert to float if needed
if delta.microseconds:
total = delta.microseconds * 1e-6
else:
total = 0
total += delta.seconds
total += delta.days * 60 * 60 * 24
return total
def scale_1024(x, n_prefixes):
'''Scale a number down to a suitable size, based on powers of 1024.
Returns the scaled number and the power of 1024 used.
Use to format numbers of bytes to KiB, MiB, etc.
>>> scale_1024(310, 3)
(310.0, 0)
>>> scale_1024(2048, 3)
(2.0, 1)
>>> scale_1024(0, 2)
(0.0, 0)
>>> scale_1024(0.5, 2)
(0.5, 0)
>>> scale_1024(1, 2)
(1.0, 0)
'''
if x <= 0:
power = 0
else:
power = min(int(math.log(x, 2) / 10), n_prefixes - 1)
scaled = float(x) / (2 ** (10 * power))
return scaled, power
def get_terminal_size(): # pragma: no cover
'''Get the current size of your terminal
Multiple returns are not always a good idea, but in this case it greatly
simplifies the code so I believe it's justified. It's not the prettiest
function but that's never really possible with cross-platform code.
Returns:
width, height: Two integers containing width and height
'''
try:
# Default to 79 characters for IPython notebooks
from IPython import get_ipython
ipython = get_ipython()
from ipykernel import zmqshell
if isinstance(ipython, zmqshell.ZMQInteractiveShell):
return 79, 24
except Exception: # pragma: no cover
pass
try:
# This works for Python 3, but not Pypy3. Probably the best method if
# it's supported so let's always try
import shutil
w, h = shutil.get_terminal_size()
if w and h:
# The off by one is needed due to progressbars in some cases, for
# safety we'll always substract it.
return w - 1, h
except Exception: # pragma: no cover
pass
try:
w = int(os.environ.get('COLUMNS'))
h = int(os.environ.get('LINES'))
if w and h:
return w, h
except Exception: # pragma: no cover
pass
try:
import blessings
terminal = blessings.Terminal()
w = terminal.width
h = terminal.height
if w and h:
return w, h
except Exception: # pragma: no cover
pass
try:
w, h = _get_terminal_size_linux()
if w and h:
return w, h
except Exception: # pragma: no cover
pass
try:
# Windows detection doesn't always work, let's try anyhow
w, h = _get_terminal_size_windows()
if w and h:
return w, h
except Exception: # pragma: no cover
pass
try:
# needed for window's python in cygwin's xterm!
w, h = _get_terminal_size_tput()
if w and h:
return w, h
except Exception: # pragma: no cover
pass
return 79, 24
def _get_terminal_size_windows(): # pragma: no cover
res = None
try:
from ctypes import windll, create_string_buffer
# stdin handle is -10
# stdout handle is -11
# stderr handle is -12
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
except Exception:
return None
if res:
import struct
(_, _, _, _, _, left, top, right, bottom, _, _) = \
struct.unpack("hhhhHhhhhhh", csbi.raw)
w = right - left
h = bottom - top
return w, h
else:
return None
def _get_terminal_size_tput(): # pragma: no cover
# get terminal width src: http://stackoverflow.com/questions/263890/
try:
import subprocess
proc = subprocess.Popen(
['tput', 'cols'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output = proc.communicate(input=None)
w = int(output[0])
proc = subprocess.Popen(
['tput', 'lines'], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output = proc.communicate(input=None)
h = int(output[0])
return w, h
except Exception:
return None
def _get_terminal_size_linux(): # pragma: no cover
def ioctl_GWINSZ(fd):
try:
import fcntl
import termios
import struct
size = struct.unpack(
'hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except Exception:
return None
return size
size = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not size:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
size = ioctl_GWINSZ(fd)
os.close(fd)
except Exception:
pass
if not size:
try:
size = os.environ['LINES'], os.environ['COLUMNS']
except Exception:
return None
return int(size[1]), int(size[0])
def format_time(tval, precision=datetime.timedelta(seconds=1)):
'''Formats timedelta/datetime/seconds
>>> format_time('1')
'0:00:01'
>>> format_time(1.234)
'0:00:01'
>>> format_time(1)
'0:00:01'
>>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> format_time(datetime.timedelta(seconds=3661))
'1:01:01'
>>> format_time(None)
'--:--:--'
>>> format_time(format_time) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Unknown type ...
'''
precision_seconds = precision.total_seconds()
if isinstance(tval, six.string_types + six.integer_types + (float, )):
try:
castfunc = six.integer_types[-1]
tval = datetime.timedelta(seconds=castfunc(tval))
except OverflowError: # pragma: no cover
tval = None
if isinstance(tval, datetime.timedelta):
seconds = tval.total_seconds()
# Truncate the number to the given precision
seconds = seconds - (seconds % precision_seconds)
return str(datetime.timedelta(seconds=seconds))
elif isinstance(tval, datetime.datetime):
# Python 2 doesn't have the timestamp method
seconds = timestamp(tval)
# Truncate the number to the given precision
seconds = seconds - (seconds % precision_seconds)
try: # pragma: no cover
if six.PY3:
dt = datetime.datetime.fromtimestamp(seconds)
else:
dt = datetime.datetime.utcfromtimestamp(seconds)
except ValueError: # pragma: no cover
dt = datetime.datetime.max
return str(dt)
elif isinstance(tval, datetime.date):
return str(tval)
elif tval is None:
return '--:--:--'
else:
raise TypeError('Unknown type %s: %r' % (type(tval), tval))
def timestamp(dt): # pragma: no cover
if hasattr(dt, 'timestamp'):
return dt.timestamp()
else:
return (dt - epoch).total_seconds()