/
pathtools.py
439 lines (348 loc) · 13.4 KB
/
pathtools.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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
"""This module defines functions for handling files and paths."""
import os
import sys
from os import sep as pathsep
from glob import glob as pyglob
import pickle as pypickle
import zipfile
import platform
import os.path
from os.path import isfile, isdir, join, split, splitext
from os.path import getsize, isabs, exists, abspath
from shutil import copy, Error as shError
from prody import PY3K
PLATFORM = platform.system()
USERHOME = os.getenv('USERPROFILE') or os.getenv('HOME')
__all__ = ['gunzip', 'backupFile', 'openFile',
'openDB', 'openSQLite', 'openURL', 'copyFile',
'isExecutable', 'isReadable', 'isWritable',
'makePath', 'relpath', 'sympath', 'which',
'pickle', 'unpickle', 'glob', 'addext',
'PLATFORM', 'USERHOME']
if PY3K:
import gzip
from gzip import GzipFile
import io
class TextIOWrapper(io.TextIOWrapper):
def _getlines(self):
try:
lines = self._lines
except AttributeError:
self._lines = None
if self._lines is None:
self._lines = self.read().split('\n')
return self._lines
def readline(self, *args):
lines = self._getlines()
if lines:
return lines.pop(0)
else:
return ''
def readlines(self, size=None):
lines = self._getlines()
if size is None:
self._lines = []
return lines
else:
self._lines = lines[size:]
return lines[:size]
def __del__(self):
self.close()
def gzip_open(filename, mode="rb", compresslevel=9,
encoding=None, errors=None, newline=None):
"""Open a gzip-compressed file in binary or text mode.
The filename argument can be an actual filename (a str or bytes object), or
an existing file object to read from or write to.
The mode argument can be "r", "rb", "w", "wb", "a" or "ab" for binary mode,
or "rt", "wt" or "at" for text mode. The default mode is "rb", and the
default compresslevel is 9.
For binary mode, this function is equivalent to the GzipFile constructor:
GzipFile(filename, mode, compresslevel). In this case, the encoding, errors
and newline arguments must not be provided.
For text mode, a GzipFile object is created, and wrapped in an
io.TextIOWrapper instance with the specified encoding, error handling
behavior, and line ending(s).
"""
if "t" in mode:
if "b" in mode:
raise ValueError("Invalid mode: %r" % (mode,))
else:
if encoding is not None:
raise ValueError("Argument 'encoding' not supported in binary mode")
if errors is not None:
raise ValueError("Argument 'errors' not supported in binary mode")
if newline is not None:
raise ValueError("Argument 'newline' not supported in binary mode")
gz_mode = mode.replace("t", "")
if isinstance(filename, (str, bytes)):
binary_file = GzipFile(filename, gz_mode, compresslevel)
elif hasattr(filename, "read") or hasattr(filename, "write"):
binary_file = GzipFile(None, gz_mode, compresslevel, filename)
else:
raise TypeError("filename must be a str or bytes object, or a file")
if "t" in mode:
return TextIOWrapper(binary_file, encoding, errors, newline)
else:
return binary_file
else:
import gzip
def gzip_open(filename, *args, **kwargs):
if args and "t" in args[0]:
args = (args[0].replace("t", ""), ) + args[1:]
if isinstance(filename, str):
return gzip.open(filename, *args, **kwargs)
else:
return gzip.GzipFile(filename, *args, **kwargs)
if PY3K:
from gzip import compress as gzip_compress
from gzip import decompress as gzip_decompress
OPEN = {
'.gz': gzip_open,
'.zip': zipfile.ZipFile,
}
def backupFile(filename, backup=None, backup_ext='.BAK', **kwargs):
"""Rename *filename* with *backup_ext* appended to its name for backup
purposes, if *backup* is **True** or if automatic backups is turned on
using :func:`.confProDy`. Default extension :file:`.BAK` is used when
one is not set using :func:`.confProDy`. If *filename* does not exist,
no action will be taken and *filename* will be returned. If file is
successfully renamed, new filename will be returned."""
try:
exists = isfile(filename)
except Exception as err:
raise TypeError('filename must be a string ({0})'.format(str(err)))
from prody import SETTINGS
if exists and (backup or SETTINGS.get('backup', False)):
if backup_ext == '.BAK':
backup_ext = SETTINGS.get('backup_ext', '.BAK')
bak = filename + backup_ext
if isfile(bak):
try:
os.remove(bak)
except Exception as err:
pass
try:
os.rename(filename, bak)
except Exception as err:
pass
return bak
else:
return filename
def openFile(filename, *args, **kwargs):
"""Open *filename* for reading, writing, or appending. First argument in
*args* is treated as the mode. Opening :file:`.gz` and :file:`.zip` files
for reading and writing is handled automatically.
:arg backup: backup existing file using :func:`.backupFile` when opening
in append or write modes, default is obtained from package settings
:type backup: bool
:arg backup_ext: extension for backup file, default is :file:`.BAK`
:type backup_ext: str"""
from prody import SETTINGS
try:
exists = isfile(filename)
except Exception as err:
raise TypeError('filename must be a string ({0})'.format(str(err)))
folder = kwargs.pop('folder', None)
if folder:
filename = join(folder, filename)
backup = kwargs.pop('backup', None)
if backup is not None and backup and args and args[0][0] in ('a', 'w'):
backupFile(filename, backup=backup,
backup_ext=kwargs.pop('backup_ext', None))
ext = splitext(filename)[1]
return OPEN.get(ext.lower(), open)(filename, *args, **kwargs)
def gunzip(filename, outname=None):
"""Returns output name that contains decompressed contents of *filename*.
When no *outname* is given, *filename* is used as the output name as it
is or after :file:`.gz` extension is removed. *filename* may also be a
string buffer, in which case decompressed string buffer or *outname* that
contains buffer will be returned."""
if len(filename) < 1000:
try:
afile = isfile(filename)
except (TypeError, ValueError):
afile = False
else:
afile = False
if afile:
if outname is None:
if filename.lower().endswith('.gz'):
outname = filename[:-3]
elif filename.lower().endswith('.tgz'):
outname = filename[:-4] + '.tar'
elif filename.lower().endswith('.gzip'):
outname = filename[:-5]
else:
outname = filename
inp = gzip_open(filename, 'rb')
data = inp.read()
inp.close()
out = open(outname, 'wb')
out.write(data)
out.close()
return outname
else:
result = None
try:
from StringIO import StringIO
except (ImportError, ModuleNotFoundError):
from io import BytesIO
buff = gzip_open(BytesIO(filename))
if outname is None:
try:
result = buff.read()
except IOError:
pass
else:
buff = buff.read()
if isinstance(buff, bytes):
with open(outname, 'wb') as out:
out.write(buff)
else:
with open(outname, 'wb') as out:
out.write(buff)
return outname
else:
from StringIO import StringIO
buff = gzip.GzipFile(fileobj=StringIO(filename))
try:
result = buff.read()
except IOError:
pass
if result is not None:
if outname is None:
return result
else:
with open(outname, 'w') as out:
out.write(result)
return outname
raise ValueError('filename is not a valid path or a compressed'
' string buffer')
def isExecutable(path):
"""Returns true if *path* is an executable."""
return (isinstance(path, str) and exists(path) and
os.access(path, os.X_OK))
def isReadable(path):
"""Returns true if *path* is readable by the user."""
return (isinstance(path, str) and exists(path) and
os.access(path, os.R_OK))
def isWritable(path):
"""Returns true if *path* is writable by the user."""
return (isinstance(path, str) and exists(path) and
os.access(path, os.W_OK))
def relpath(path):
"""Returns *path* on Windows, and relative path elsewhere."""
if PLATFORM == 'Windows':
return path
else:
return os.path.relpath(path)
def sympath(path, beg=2, end=1, ellipsis='...'):
"""Returns a symbolic path for a long *path*, by replacing folder names
in the middle with *ellipsis*. *beg* and *end* specified how many folder
(or file) names to include from the beginning and end of the path."""
abs_items = abspath(path).split(pathsep)
rel_items = relpath(path).split(pathsep)
if len(abs_items) <= len(rel_items):
items = abs_items
else:
items = rel_items
if len(items) <= beg + end:
return pathsep.join(items)
else:
return pathsep.join(items[:beg+1] + [ellipsis] + items[-end:])
def makePath(path):
"""Make all directories that does not exist in a given *path*."""
if not isdir(path):
dirs = path.split(pathsep)
for i, dirname in enumerate(dirs):
if not dirname:
continue
dirname = pathsep.join(dirs[:i+1])
try:
if not isdir(dirname):
os.mkdir(dirname)
except OSError:
raise OSError('{0} could not be created, please '
'specify another path'.format(path))
return path
def which(program):
"""This function is based on the example in:
http://stackoverflow.com/questions/377017/"""
fpath, fname = os.path.split(program)
fname, fext = os.path.splitext(fname)
if fpath and isExecutable(program):
return program
else:
if os.name == 'nt' and fext == '':
program += '.exe'
for path in os.environ["PATH"].split(os.pathsep):
path = os.path.join(path, program)
if isExecutable(path):
return path
return None
def pickle(obj, filename, protocol=2, **kwargs):
"""Pickle *obj* using :func:`pickle.dump` in *filename*. *protocol* is set
to 2 for compatibility between Python 2 and 3."""
out = openFile(filename, 'wb', **kwargs)
pypickle.dump(obj, out, protocol=2)
out.close()
return filename
def unpickle(filename, **kwargs):
"""Unpickle object in *filename* using :func:`pickle.load`."""
inf = openFile(filename, 'rb', **kwargs)
obj = pypickle.load(inf)
inf.close()
return obj
def openDB(filename, *args):
"""Open a database with given *filename*."""
try:
import anydbm as dbm
except ImportError:
import dbm
return dbm.open(filename, *args)
def openSQLite(filename, *args):
"""Returns a connection to SQLite database *filename*. If ``'n'`` argument
is passed, remove any existing databases with the same name and return
connection to a new empty database."""
if 'n' in args and isfile(filename):
os.remove(filename)
import sqlite3
return sqlite3.connect(filename)
def openURL(url, timeout=5, **kwargs):
"""Open *url* for reading. Raise an :exc:`IOError` if *url* cannot be
reached. Small *timeout* values are suitable if *url* is an ip address.
*kwargs* will be used to make :class:`urllib.request.Request` instance
for opening the *url*."""
try:
from urllib2 import urlopen, URLError, Request
except ImportError:
from urllib.request import urlopen, Request
from urllib.error import URLError
if kwargs:
request = Request(url, **kwargs)
else:
request = str(url)
try:
return urlopen(request, timeout=int(timeout))
except URLError:
raise IOError('{0} could not be opened for reading, invalid URL or '
'no internet connection'.format(repr(request)))
def glob(*pathnames):
"""Returns concatenation of ordered lists of paths matching patterns in
*pathnames*."""
paths = []
for pathname in pathnames:
matches = pyglob(pathname)
matches.sort()
paths.extend(matches)
return paths
def copyFile(src, dst):
"""Returns *dst*, a copy of *src*."""
try:
copy(src, dst)
except shError:
return dst
return dst
def addext(filename, extension):
"""Returns *filename*, with *extension* if it does not have one."""
return filename + ('' if splitext(filename)[1] else extension)