| 1 |
# -*- coding: utf-8 -*- |
| 2 |
from __future__ import absolute_import, print_function, division |
| 3 |
|
| 4 |
|
| 5 |
import os |
| 6 |
import io |
| 7 |
import gzip |
| 8 |
import sys |
| 9 |
import bz2 |
| 10 |
import zipfile |
| 11 |
from contextlib import contextmanager |
| 12 |
import subprocess |
| 13 |
import logging |
| 14 |
|
| 15 |
|
| 16 |
from petl.errors import ArgumentError |
| 17 |
from petl.compat import urlopen, StringIO, BytesIO, string_types, PY2 |
| 18 |
|
| 19 |
|
| 20 |
logger = logging.getLogger(__name__) |
| 21 |
warning = logger.warning |
| 22 |
info = logger.info |
| 23 |
debug = logger.debug |
| 24 |
|
| 25 |
|
| 26 |
class FileSource(object): |
| 27 |
|
| 28 |
def __init__(self, filename, **kwargs): |
| 29 |
self.filename = filename |
| 30 |
self.kwargs = kwargs |
| 31 |
|
| 32 |
def open(self, mode='r'): |
| 33 |
return io.open(self.filename, mode, **self.kwargs) |
| 34 |
|
| 35 |
|
| 36 |
class GzipSource(object): |
| 37 |
|
| 38 |
def __init__(self, filename, remote=False, **kwargs): |
| 39 |
self.filename = filename |
| 40 |
self.remote = remote |
| 41 |
self.kwargs = kwargs |
| 42 |
|
| 43 |
@contextmanager |
| 44 |
def open(self, mode='r'): |
| 45 |
if self.remote: |
| 46 |
if not mode.startswith('r'): |
| 47 |
raise ArgumentError('source is read-only') |
| 48 |
filehandle = urlopen(self.filename) |
| 49 |
else: |
| 50 |
filehandle = self.filename |
| 51 |
source = gzip.open(filehandle, mode, **self.kwargs) |
| 52 |
try: |
| 53 |
yield source |
| 54 |
finally: |
| 55 |
source.close() |
| 56 |
|
| 57 |
|
| 58 |
class BZ2Source(object): |
| 59 |
|
| 60 |
def __init__(self, filename, remote=False, **kwargs): |
| 61 |
self.filename = filename |
| 62 |
self.remote = remote |
| 63 |
self.kwargs = kwargs |
| 64 |
|
| 65 |
@contextmanager |
| 66 |
def open(self, mode='r'): |
| 67 |
if self.remote: |
| 68 |
if not mode.startswith('r'): |
| 69 |
raise ArgumentError('source is read-only') |
| 70 |
filehandle = urlopen(self.filename) |
| 71 |
else: |
| 72 |
filehandle = self.filename |
| 73 |
source = bz2.BZ2File(filehandle, mode, **self.kwargs) |
| 74 |
try: |
| 75 |
yield source |
| 76 |
finally: |
| 77 |
source.close() |
| 78 |
|
| 79 |
|
| 80 |
class ZipSource(object): |
| 81 |
|
| 82 |
def __init__(self, filename, membername, pwd=None, **kwargs): |
| 83 |
self.filename = filename |
| 84 |
self.membername = membername |
| 85 |
self.pwd = pwd |
| 86 |
self.kwargs = kwargs |
| 87 |
|
| 88 |
@contextmanager |
| 89 |
def open(self, mode): |
| 90 |
if PY2: |
| 91 |
mode = mode.translate(None, 'bU') |
| 92 |
else: |
| 93 |
mode = mode.translate({ord('b'): None, ord('U'): None}) |
| 94 |
zf = zipfile.ZipFile(self.filename, mode, **self.kwargs) |
| 95 |
try: |
| 96 |
if self.pwd is not None: |
| 97 |
yield zf.open(self.membername, mode, self.pwd) |
| 98 |
else: |
| 99 |
yield zf.open(self.membername, mode) |
| 100 |
finally: |
| 101 |
zf.close() |
| 102 |
|
| 103 |
|
| 104 |
class Uncloseable(object): |
| 105 |
|
| 106 |
def __init__(self, inner): |
| 107 |
object.__setattr__(self, '_inner', inner) |
| 108 |
|
| 109 |
def __getattr__(self, item): |
| 110 |
return getattr(self._inner, item) |
| 111 |
|
| 112 |
def __setattr__(self, key, value): |
| 113 |
setattr(self._inner, key, value) |
| 114 |
|
| 115 |
def close(self): |
| 116 |
debug('Uncloseable: close called (%r)' % self._inner) |
| 117 |
pass |
| 118 |
|
| 119 |
|
| 120 |
def _get_stdout_binary(): |
| 121 |
try: |
| 122 |
return sys.stdout.buffer |
| 123 |
except AttributeError: |
| 124 |
pass |
| 125 |
try: |
| 126 |
fd = sys.stdout.fileno() |
| 127 |
return os.fdopen(fd, 'ab', 0) |
| 128 |
except Exception: |
| 129 |
pass |
| 130 |
try: |
| 131 |
return sys.__stdout__.buffer |
| 132 |
except AttributeError: |
| 133 |
pass |
| 134 |
try: |
| 135 |
fd = sys.__stdout__.fileno() |
| 136 |
return os.fdopen(fd, 'ab', 0) |
| 137 |
except Exception: |
| 138 |
pass |
| 139 |
# fallback |
| 140 |
return sys.stdout |
| 141 |
|
| 142 |
|
| 143 |
stdout_binary = _get_stdout_binary() |
| 144 |
|
| 145 |
|
| 146 |
def _get_stdin_binary(): |
| 147 |
try: |
| 148 |
return sys.stdin.buffer |
| 149 |
except AttributeError: |
| 150 |
pass |
| 151 |
try: |
| 152 |
fd = sys.stdin.fileno() |
| 153 |
return os.fdopen(fd, 'rb', 0) |
| 154 |
except Exception: |
| 155 |
pass |
| 156 |
try: |
| 157 |
return sys.__stdin__.buffer |
| 158 |
except AttributeError: |
| 159 |
pass |
| 160 |
try: |
| 161 |
fd = sys.__stdin__.fileno() |
| 162 |
return os.fdopen(fd, 'rb', 0) |
| 163 |
except Exception: |
| 164 |
pass |
| 165 |
# fallback |
| 166 |
return sys.stdin |
| 167 |
|
| 168 |
|
| 169 |
stdin_binary = _get_stdin_binary() |
| 170 |
|
| 171 |
|
| 172 |
class StdoutSource(object): |
| 173 |
|
| 174 |
@contextmanager |
| 175 |
def open(self, mode): |
| 176 |
if mode.startswith('r'): |
| 177 |
raise ArgumentError('source is write-only') |
| 178 |
if 'b' in mode: |
| 179 |
yield Uncloseable(stdout_binary) |
| 180 |
else: |
| 181 |
yield Uncloseable(sys.stdout) |
| 182 |
|
| 183 |
|
| 184 |
class StdinSource(object): |
| 185 |
|
| 186 |
@contextmanager |
| 187 |
def open(self, mode='r'): |
| 188 |
if not mode.startswith('r'): |
| 189 |
raise ArgumentError('source is read-only') |
| 190 |
if 'b' in mode: |
| 191 |
yield Uncloseable(stdin_binary) |
| 192 |
else: |
| 193 |
yield Uncloseable(sys.stdin) |
| 194 |
|
| 195 |
|
| 196 |
class URLSource(object): |
| 197 |
|
| 198 |
def __init__(self, *args, **kwargs): |
| 199 |
self.args = args |
| 200 |
self.kwargs = kwargs |
| 201 |
|
| 202 |
@contextmanager |
| 203 |
def open(self, mode='r'): |
| 204 |
if not mode.startswith('r'): |
| 205 |
raise ArgumentError('source is read-only') |
| 206 |
f = urlopen(*self.args, **self.kwargs) |
| 207 |
try: |
| 208 |
yield f |
| 209 |
finally: |
| 210 |
f.close() |
| 211 |
|
| 212 |
|
| 213 |
class MemorySource(object): |
| 214 |
"""Memory data source. E.g.:: |
| 215 |
|
| 216 |
>>> import petl as etl |
| 217 |
>>> data = b'foo,bar\\na,1\\nb,2\\nc,2\\n' |
| 218 |
>>> source = etl.MemorySource(data) |
| 219 |
>>> tbl = etl.fromcsv(source) |
| 220 |
>>> tbl |
| 221 |
+-----+-----+ |
| 222 |
| foo | bar | |
| 223 |
+=====+=====+ |
| 224 |
| 'a' | '1' | |
| 225 |
+-----+-----+ |
| 226 |
| 'b' | '2' | |
| 227 |
+-----+-----+ |
| 228 |
| 'c' | '2' | |
| 229 |
+-----+-----+ |
| 230 |
|
| 231 |
>>> sink = etl.MemorySource() |
| 232 |
>>> tbl.tojson(sink) |
| 233 |
>>> sink.getvalue() |
| 234 |
b'[{"foo": "a", "bar": "1"}, {"foo": "b", "bar": "2"}, {"foo": "c", "bar": "2"}]' |
| 235 |
|
| 236 |
Also supports appending. |
| 237 |
|
| 238 |
""" |
| 239 |
|
| 240 |
def __init__(self, s=None): |
| 241 |
self.s = s |
| 242 |
self.buffer = None |
| 243 |
|
| 244 |
@contextmanager |
| 245 |
def open(self, mode='rb'): |
| 246 |
try: |
| 247 |
if 'r' in mode: |
| 248 |
if self.s is not None: |
| 249 |
if 'b' in mode: |
| 250 |
self.buffer = BytesIO(self.s) |
| 251 |
else: |
| 252 |
self.buffer = StringIO(self.s) |
| 253 |
else: |
| 254 |
raise ArgumentError('no string data supplied') |
| 255 |
elif 'w' in mode: |
| 256 |
if self.buffer is not None: |
| 257 |
self.buffer.close() |
| 258 |
if 'b' in mode: |
| 259 |
self.buffer = BytesIO() |
| 260 |
else: |
| 261 |
self.buffer = StringIO() |
| 262 |
elif 'a' in mode: |
| 263 |
if self.buffer is None: |
| 264 |
if 'b' in mode: |
| 265 |
self.buffer = BytesIO() |
| 266 |
else: |
| 267 |
self.buffer = StringIO() |
| 268 |
yield Uncloseable(self.buffer) |
| 269 |
except: |
| 270 |
raise |
| 271 |
finally: |
| 272 |
pass # don't close the buffer |
| 273 |
|
| 274 |
def getvalue(self): |
| 275 |
if self.buffer: |
| 276 |
return self.buffer.getvalue() |
| 277 |
|
| 278 |
|
| 279 |
# backwards compatibility |
| 280 |
StringSource = MemorySource |
| 281 |
|
| 282 |
|
| 283 |
class PopenSource(object): |
| 284 |
|
| 285 |
def __init__(self, *args, **kwargs): |
| 286 |
self.args = args |
| 287 |
self.kwargs = kwargs |
| 288 |
|
| 289 |
@contextmanager |
| 290 |
def open(self, mode='r'): |
| 291 |
if not mode.startswith('r'): |
| 292 |
raise ArgumentError('source is read-only') |
| 293 |
self.kwargs['stdout'] = subprocess.PIPE |
| 294 |
proc = subprocess.Popen(*self.args, **self.kwargs) |
| 295 |
try: |
| 296 |
yield proc.stdout |
| 297 |
finally: |
| 298 |
pass |
| 299 |
|
| 300 |
|
| 301 |
class CompressedSource(object): |
| 302 |
'''Handle IO from a file-like object and (de)compress with a codec |
| 303 |
|
| 304 |
The `source` argument (source class) is the source class that will handle |
| 305 |
the actual input/output stream. E.g: :class:`petl.io.sources.URLSource`. |
| 306 |
|
| 307 |
The `codec` argument (source class) is the source class that will handle |
| 308 |
the (de)compression of the stream. E.g: :class:`petl.io.sources.GzipSource`. |
| 309 |
''' |
| 310 |
|
| 311 |
def __init__(self, source, codec): |
| 312 |
self.source = source |
| 313 |
self.codec = codec |
| 314 |
|
| 315 |
@contextmanager |
| 316 |
def open(self, mode='rb'): |
| 317 |
with self.source.open(mode=mode) as filehandle: |
| 318 |
transcoder = self.codec(filehandle) |
| 319 |
with transcoder.open(mode=mode) as stream: |
| 320 |
yield stream |
| 321 |
|
| 322 |
|
| 323 |
_invalid_source_msg = 'invalid source argument, expected None or a string or ' \ |
| 324 |
'an object implementing open(), found %r' |
| 325 |
|
| 326 |
|
| 327 |
_READERS = {} |
| 328 |
_CODECS = {} |
| 329 |
_WRITERS = {} |
| 330 |
|
| 331 |
|
| 332 |
def _assert_source_has_open(source_class): |
| 333 |
source = source_class('test') |
| 334 |
assert (hasattr(source, 'open') |
| 335 |
and callable(getattr(source, 'open'))), \ |
| 336 |
_invalid_source_msg % source |
| 337 |
|
| 338 |
|
| 339 |
def _register_handler(handler_type, handler_class, handler_list): |
| 340 |
|
| 341 |
assert isinstance(handler_type, string_types), _invalid_source_msg % handler_type |
| 342 |
assert isinstance(handler_class, type), _invalid_source_msg % handler_type |
| 343 |
_assert_source_has_open(handler_class) |
| 344 |
handler_list[handler_type] = handler_class |
| 345 |
|
| 346 |
|
| 347 |
def _get_handler(handler_type, handler_list): |
| 348 |
|
| 349 |
if isinstance(handler_type, string_types): |
| 350 |
if handler_type in handler_list: |
| 351 |
return handler_list[handler_type] |
| 352 |
return None |
| 353 |
|
| 354 |
|
| 355 |
def register_codec(extension, handler_class): |
| 356 |
''' |
| 357 |
Register handler for automatic compression and decompression for file I/O |
| 358 |
|
| 359 |
Use of the handler is determined matching the file `extension` with the |
| 360 |
source specified in ``from...()`` and ``to...()`` functions. |
| 361 |
|
| 362 |
.. versionadded:: 1.5.0 |
| 363 |
''' |
| 364 |
_register_handler(extension, handler_class, _CODECS) |
| 365 |
|
| 366 |
|
| 367 |
def register_reader(protocol, handler_class): |
| 368 |
''' |
| 369 |
Register handler for automatic reading using a remote protocol. |
| 370 |
|
| 371 |
Use of the handler is determined matching the `protocol` with the scheme |
| 372 |
part of the url in ``from...()`` function (e.g: `http://`). |
| 373 |
|
| 374 |
.. versionadded:: 1.5.0 |
| 375 |
''' |
| 376 |
_register_handler(protocol, handler_class, _READERS) |
| 377 |
|
| 378 |
|
| 379 |
def register_writer(protocol, handler_class): |
| 380 |
''' |
| 381 |
Register handler for automatic writing using a remote protocol. |
| 382 |
|
| 383 |
Use of the handler is determined matching the `protocol` with the scheme |
| 384 |
part of the url in ``to...()`` function (e.g: `smb://`). |
| 385 |
|
| 386 |
.. versionadded:: 1.5.0 |
| 387 |
''' |
| 388 |
_register_handler(protocol, handler_class, _WRITERS) |
| 389 |
|
| 390 |
|
| 391 |
def get_reader(protocol): |
| 392 |
''' |
| 393 |
Retrieve the handler responsible for reading from a remote protocol. |
| 394 |
|
| 395 |
.. versionadded:: 1.6.0 |
| 396 |
''' |
| 397 |
return _get_handler(protocol, _READERS) |
| 398 |
|
| 399 |
|
| 400 |
def get_writer(protocol): |
| 401 |
''' |
| 402 |
Retrieve the handler responsible for writing from a remote protocol. |
| 403 |
|
| 404 |
.. versionadded:: 1.6.0 |
| 405 |
''' |
| 406 |
return _get_handler(protocol, _WRITERS) |
| 407 |
|
| 408 |
|
| 409 |
# Setup default sources |
| 410 |
|
| 411 |
register_codec('.gz', GzipSource) |
| 412 |
register_codec('.bgz', GzipSource) |
| 413 |
register_codec('.bz2', BZ2Source) |
| 414 |
|
| 415 |
register_reader('ftp', URLSource) |
| 416 |
register_reader('http', URLSource) |
| 417 |
register_reader('https', URLSource) |
| 418 |
|
| 419 |
|
| 420 |
def _get_codec_for(source): |
| 421 |
for ext, codec_class in _CODECS.items(): |
| 422 |
if source.endswith(ext): |
| 423 |
return codec_class |
| 424 |
return None |
| 425 |
|
| 426 |
|
| 427 |
def _get_handler_from(source, handlers): |
| 428 |
protocol_index = source.find('://') |
| 429 |
if protocol_index <= 0: |
| 430 |
return None |
| 431 |
protocol = source[:protocol_index] |
| 432 |
for prefix, handler_class in handlers.items(): |
| 433 |
if prefix == protocol: |
| 434 |
return handler_class |
| 435 |
return None |
| 436 |
|
| 437 |
|
| 438 |
def _resolve_source_from_arg(source, handlers): |
| 439 |
if isinstance(source, string_types): |
| 440 |
handler = _get_handler_from(source, handlers) |
| 441 |
codec = _get_codec_for(source) |
| 442 |
if handler is None: |
| 443 |
if codec is not None: |
| 444 |
return codec(source) |
| 445 |
assert '://' not in source, _invalid_source_msg % source |
| 446 |
return FileSource(source) |
| 447 |
return handler(source) |
| 448 |
else: |
| 449 |
assert (hasattr(source, 'open') |
| 450 |
and callable(getattr(source, 'open'))), \ |
| 451 |
_invalid_source_msg % source |
| 452 |
return source |
| 453 |
|
| 454 |
|
| 455 |
def read_source_from_arg(source): |
| 456 |
''' |
| 457 |
Retrieve a open stream for reading from the source provided. |
| 458 |
|
| 459 |
The result stream will be open by a handler that would return raw bytes and |
| 460 |
transparently take care of the decompression, remote authentication, |
| 461 |
network transfer, format decoding, and data extraction. |
| 462 |
|
| 463 |
.. versionadded:: 1.4.0 |
| 464 |
''' |
| 465 |
if source is None: |
| 466 |
return StdinSource() |
| 467 |
return _resolve_source_from_arg(source, _READERS) |
| 468 |
|
| 469 |
|
| 470 |
def write_source_from_arg(source, mode='wb'): |
| 471 |
''' |
| 472 |
Retrieve a open stream for writing to the source provided. |
| 473 |
|
| 474 |
The result stream will be open by a handler that would write raw bytes and |
| 475 |
transparently take care of the compression, remote authentication, |
| 476 |
network transfer, format encoding, and data writing. |
| 477 |
|
| 478 |
.. versionadded:: 1.4.0 |
| 479 |
''' |
| 480 |
if source is None: |
| 481 |
return StdoutSource() |
| 482 |
return _resolve_source_from_arg(source, _WRITERS) |