-
Notifications
You must be signed in to change notification settings - Fork 1
/
sas7bdat.py
1624 lines (1513 loc) · 62.7 KB
/
sas7bdat.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
This module will read sas7bdat files using pure Python (2.7+, 3+).
No SAS software required!
"""
from __future__ import division, absolute_import, print_function,\
unicode_literals
import atexit
import csv
import logging
import math
import os
import platform
import struct
import sys
from datetime import datetime, timedelta
import six
xrange = six.moves.range
__all__ = ['SAS7BDAT']
def _debug(t, v, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
sys.__excepthook__(t, v, tb)
else:
import pdb
import traceback
traceback.print_exception(t, v, tb)
print()
pdb.pm()
os._exit(1)
def _get_color_emit(prefix, fn):
# This doesn't work on Windows since Windows doesn't support
# the ansi escape characters
def _new(handler):
levelno = handler.levelno
if levelno >= logging.CRITICAL:
color = '\x1b[31m' # red
elif levelno >= logging.ERROR:
color = '\x1b[31m' # red
elif levelno >= logging.WARNING:
color = '\x1b[33m' # yellow
elif levelno >= logging.INFO:
color = '\x1b[32m' # green or normal
elif levelno >= logging.DEBUG:
color = '\x1b[35m' # pink
else:
color = '\x1b[0m' # normal
handler.msg = '%s[%s] %s%s' % (color, prefix, handler.msg, '\x1b[0m')
return fn(handler)
return _new
class ParseError(Exception):
pass
class Decompressor(object):
def __init__(self, parent):
self.parent = parent
def decompress_row(self, offset, length, result_length, page):
raise NotImplementedError
@staticmethod
def to_ord(int_or_str):
if isinstance(int_or_str, int):
return int_or_str
return ord(int_or_str)
@staticmethod
def to_chr(int_or_str):
py2 = six.PY2
if isinstance(int_or_str, (bytes, bytearray)):
return int_or_str
if py2:
return chr(int_or_str)
return bytes([int_or_str])
class RLEDecompressor(Decompressor):
"""
Decompresses data using the Run Length Encoding algorithm
"""
def decompress_row(self, offset, length, result_length, page):
b = self.to_ord
c = self.to_chr
current_result_array_index = 0
result = []
i = 0
for j in xrange(length):
if i != j:
continue
control_byte = b(page[offset + i]) & 0xF0
end_of_first_byte = b(page[offset + i]) & 0x0F
if control_byte == 0x00:
if i != (length - 1):
count_of_bytes_to_copy = (
(b(page[offset + i + 1]) & 0xFF) +
64 +
end_of_first_byte * 256
)
start = offset + i + 2
end = start + count_of_bytes_to_copy
result.append(c(page[start:end]))
i += count_of_bytes_to_copy + 1
current_result_array_index += count_of_bytes_to_copy
elif control_byte == 0x40:
copy_counter = (
end_of_first_byte * 16 +
(b(page[offset + i + 1]) & 0xFF)
)
for _ in xrange(copy_counter + 18):
result.append(c(page[offset + i + 2]))
current_result_array_index += 1
i += 2
elif control_byte == 0x60:
for _ in xrange(end_of_first_byte * 256 +
(b(page[offset + i + 1]) & 0xFF) + 17):
result.append(c(0x20))
current_result_array_index += 1
i += 1
elif control_byte == 0x70:
for _ in xrange((b(page[offset + i + 1]) & 0xFF) + 17):
result.append(c(0x00))
current_result_array_index += 1
i += 1
elif control_byte == 0x80:
count_of_bytes_to_copy = min(end_of_first_byte + 1,
length - (i + 1))
start = offset + i + 1
end = start + count_of_bytes_to_copy
result.append(c(page[start:end]))
i += count_of_bytes_to_copy
current_result_array_index += count_of_bytes_to_copy
elif control_byte == 0x90:
count_of_bytes_to_copy = min(end_of_first_byte + 17,
length - (i + 1))
start = offset + i + 1
end = start + count_of_bytes_to_copy
result.append(c(page[start:end]))
i += count_of_bytes_to_copy
current_result_array_index += count_of_bytes_to_copy
elif control_byte == 0xA0:
count_of_bytes_to_copy = min(end_of_first_byte + 33,
length - (i + 1))
start = offset + i + 1
end = start + count_of_bytes_to_copy
result.append(c(page[start:end]))
i += count_of_bytes_to_copy
current_result_array_index += count_of_bytes_to_copy
elif control_byte == 0xB0:
count_of_bytes_to_copy = min(end_of_first_byte + 49,
length - (i + 1))
start = offset + i + 1
end = start + count_of_bytes_to_copy
result.append(c(page[start:end]))
i += count_of_bytes_to_copy
current_result_array_index += count_of_bytes_to_copy
elif control_byte == 0xC0:
for _ in xrange(end_of_first_byte + 3):
result.append(c(page[offset + i + 1]))
current_result_array_index += 1
i += 1
elif control_byte == 0xD0:
for _ in xrange(end_of_first_byte + 2):
result.append(c(0x40))
current_result_array_index += 1
elif control_byte == 0xE0:
for _ in xrange(end_of_first_byte + 2):
result.append(c(0x20))
current_result_array_index += 1
elif control_byte == 0xF0:
for _ in xrange(end_of_first_byte + 2):
result.append(c(0x00))
current_result_array_index += 1
else:
self.parent.logger.error('unknown control byte: %s',
control_byte)
i += 1
return b''.join(result)
class RDCDecompressor(Decompressor):
"""
Decompresses data using the Ross Data Compression algorithm
"""
def bytes_to_bits(self, src, offset, length):
result = [0] * (length * 8)
for i in xrange(length):
b = src[offset + i]
for bit in xrange(8):
result[8 * i + (7 - bit)] = 0 if ((b & (1 << bit)) == 0) else 1
return result
def ensure_capacity(self, src, capacity):
if capacity >= len(src):
new_len = max(capacity, 2 * len(src))
src.extend([0] * (new_len - len(src)))
return src
def is_short_rle(self, first_byte_of_cb):
return first_byte_of_cb in set([0x00, 0x01, 0x02, 0x03, 0x04, 0x05])
def is_single_byte_marker(self, first_byte_of_cb):
return first_byte_of_cb in set([0x02, 0x04, 0x06, 0x08, 0x0A])
def is_two_bytes_marker(self, double_bytes_cb):
return len(double_bytes_cb) == 2 and\
((double_bytes_cb[0] >> 4) & 0xF) > 2
def is_three_bytes_marker(self, three_byte_marker):
flag = three_byte_marker[0] >> 4
return len(three_byte_marker) == 3 and (flag & 0xF) in set([1, 2])
def get_length_of_rle_pattern(self, first_byte_of_cb):
if first_byte_of_cb <= 0x05:
return first_byte_of_cb + 3
return 0
def get_length_of_one_byte_pattern(self, first_byte_of_cb):
return first_byte_of_cb + 14\
if self.is_single_byte_marker(first_byte_of_cb) else 0
def get_length_of_two_bytes_pattern(self, double_bytes_cb):
return (double_bytes_cb[0] >> 4) & 0xF
def get_length_of_three_bytes_pattern(self, p_type, three_byte_marker):
if p_type == 1:
return 19 + (three_byte_marker[0] & 0xF) +\
(three_byte_marker[1] * 16)
elif p_type == 2:
return three_byte_marker[2] + 16
return 0
def get_offset_for_one_byte_pattern(self, first_byte_of_cb):
if first_byte_of_cb == 0x08:
return 24
elif first_byte_of_cb == 0x0A:
return 40
return 0
def get_offset_for_two_bytes_pattern(self, double_bytes_cb):
return 3 + (double_bytes_cb[0] & 0xF) + (double_bytes_cb[1] * 16)
def get_offset_for_three_bytes_pattern(self, triple_bytes_cb):
return 3 + (triple_bytes_cb[0] & 0xF) + (triple_bytes_cb[1] * 16)
def clone_byte(self, b, length):
return [b] * length
def decompress_row(self, offset, length, result_length, page):
b = self.to_ord
c = self.to_chr
src_row = [b(x) for x in page[offset:offset + length]]
out_row = [0] * result_length
src_offset = 0
out_offset = 0
while src_offset < (len(src_row) - 2):
prefix_bits = self.bytes_to_bits(src_row, src_offset, 2)
src_offset += 2
for bit_index in xrange(16):
if src_offset >= len(src_row):
break
if prefix_bits[bit_index] == 0:
out_row = self.ensure_capacity(out_row, out_offset)
out_row[out_offset] = src_row[src_offset]
src_offset += 1
out_offset += 1
continue
marker_byte = src_row[src_offset]
try:
next_byte = src_row[src_offset + 1]
except IndexError:
break
if self.is_short_rle(marker_byte):
length = self.get_length_of_rle_pattern(marker_byte)
out_row = self.ensure_capacity(
out_row, out_offset + length
)
pattern = self.clone_byte(next_byte, length)
out_row[out_offset:out_offset + length] = pattern
out_offset += length
src_offset += 2
continue
elif self.is_single_byte_marker(marker_byte) and not\
((next_byte & 0xF0) == ((next_byte << 4) & 0xF0)):
length = self.get_length_of_one_byte_pattern(marker_byte)
out_row = self.ensure_capacity(
out_row, out_offset + length
)
back_offset = self.get_offset_for_one_byte_pattern(
marker_byte
)
start = out_offset - back_offset
end = start + length
out_row[out_offset:out_offset + length] =\
out_row[start:end]
src_offset += 1
out_offset += length
continue
two_bytes_marker = src_row[src_offset:src_offset + 2]
if self.is_two_bytes_marker(two_bytes_marker):
length = self.get_length_of_two_bytes_pattern(
two_bytes_marker
)
out_row = self.ensure_capacity(
out_row, out_offset + length
)
back_offset = self.get_offset_for_two_bytes_pattern(
two_bytes_marker
)
start = out_offset - back_offset
end = start + length
out_row[out_offset:out_offset + length] =\
out_row[start:end]
src_offset += 2
out_offset += length
continue
three_bytes_marker = src_row[src_offset:src_offset + 3]
if self.is_three_bytes_marker(three_bytes_marker):
p_type = (three_bytes_marker[0] >> 4) & 0x0F
back_offset = 0
if p_type == 2:
back_offset = self.get_offset_for_three_bytes_pattern(
three_bytes_marker
)
length = self.get_length_of_three_bytes_pattern(
p_type, three_bytes_marker
)
out_row = self.ensure_capacity(
out_row, out_offset + length
)
if p_type == 1:
pattern = self.clone_byte(
three_bytes_marker[2], length
)
else:
start = out_offset - back_offset
end = start + length
pattern = out_row[start:end]
out_row[out_offset:out_offset + length] = pattern
src_offset += 3
out_offset += length
continue
else:
self.parent.logger.error(
'unknown marker %s at offset %s', src_row[src_offset],
src_offset
)
break
return b''.join([c(x) for x in out_row])
class SAS7BDAT(object):
"""
SAS7BDAT(path[, log_level[, extra_time_format_strings[, \
extra_date_time_format_strings[, extra_date_format_strings]]]]) -> \
SAS7BDAT object
Open a SAS7BDAT file. The log level are standard logging levels
(defaults to logging.INFO).
If your sas7bdat file uses non-standard format strings for time, datetime,
or date values, pass those strings into the constructor using the
appropriate kwarg.
"""
_open_files = []
RLE_COMPRESSION = b'SASYZCRL'
RDC_COMPRESSION = b'SASYZCR2'
COMPRESSION_LITERALS = set([
RLE_COMPRESSION, RDC_COMPRESSION
])
DECOMPRESSORS = {
RLE_COMPRESSION: RLEDecompressor,
RDC_COMPRESSION: RDCDecompressor
}
TIME_FORMAT_STRINGS = set([
'TIME'
])
DATE_TIME_FORMAT_STRINGS = set([
'DATETIME'
])
DATE_FORMAT_STRINGS = set([
'YYMMDD', 'MMDDYY', 'DDMMYY', 'DATE', 'JULIAN', 'MONYY'
])
def __init__(self, path, log_level=logging.INFO,
extra_time_format_strings=None,
extra_date_time_format_strings=None,
extra_date_format_strings=None,
skip_header=False,
encoding='utf8',
encoding_errors='ignore',
align_correction=True):
"""
x.__init__(...) initializes x; see help(type(x)) for signature
"""
if log_level == logging.DEBUG:
sys.excepthook = _debug
self.path = path
self.endianess = None
self.u64 = False
self.logger = self._make_logger(level=log_level)
self._update_format_strings(
self.TIME_FORMAT_STRINGS, extra_time_format_strings
)
self._update_format_strings(
self.DATE_TIME_FORMAT_STRINGS, extra_date_time_format_strings
)
self._update_format_strings(
self.DATE_FORMAT_STRINGS, extra_date_format_strings
)
self.skip_header = skip_header
self.encoding = encoding
self.encoding_errors = encoding_errors
self.align_correction = align_correction
self._file = open(self.path, 'rb')
self._open_files.append(self._file)
self.cached_page = None
self.current_page_type = None
self.current_page_block_count = None
self.current_page_subheaders_count = None
self.current_file_position = 0
self.current_page_data_subheader_pointers = []
self.current_row = []
self.column_names_strings = []
self.column_names = []
self.column_types = []
self.column_data_offsets = []
self.column_data_lengths = []
self.columns = []
self.header = SASHeader(self)
self.properties = self.header.properties
self.header.parse_metadata()
self.logger.debug('\n%s', str(self.header))
self._iter = self.readlines()
def __repr__(self):
"""
x.__repr__() <==> repr(x)
"""
return 'SAS7BDAT file: %s' % os.path.basename(self.path)
def __enter__(self):
"""
__enter__() -> self.
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
__exit__(*excinfo) -> None. Closes the file.
"""
self.close()
def __iter__(self):
"""
x.__iter__() <==> iter(x)
"""
return self.readlines()
def _update_format_strings(self, var, format_strings):
if format_strings is not None:
if isinstance(format_strings, str):
var.add(format_strings)
elif isinstance(format_strings, (set, list, tuple)):
var.update(set(format_strings))
else:
raise NotImplementedError
def close(self):
"""
close() -> None or (perhaps) an integer. Close the file.
A closed file cannot be used for further I/O operations.
close() may be called more than once without error.
Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
"""
return self._file.close()
def _make_logger(self, level=logging.INFO):
"""
Create a custom logger with the specified properties.
"""
logger = logging.getLogger(self.path)
logger.setLevel(level)
fmt = '%(message)s'
stream_handler = logging.StreamHandler()
if platform.system() != 'Windows':
stream_handler.emit = _get_color_emit(
os.path.basename(self.path),
stream_handler.emit
)
else:
fmt = '[%s] %%(message)s' % os.path.basename(self.path)
formatter = logging.Formatter(fmt, '%y-%m-%d %H:%M:%S')
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
def _read_bytes(self, offsets_to_lengths):
result = {}
if not self.cached_page:
for offset, length in six.iteritems(offsets_to_lengths):
skipped = 0
while skipped < (offset - self.current_file_position):
seek = offset - self.current_file_position - skipped
skipped += seek
self._file.seek(seek, 0)
tmp = self._file.read(length)
if len(tmp) < length:
self.logger.error(
'failed to read %s bytes from sas7bdat file', length
)
self.current_file_position = offset + length
result[offset] = tmp
else:
for offset, length in six.iteritems(offsets_to_lengths):
result[offset] = self.cached_page[offset:offset + length]
return result
def _read_val(self, fmt, raw_bytes, size):
if fmt == 'i' and self.u64 and size == 8:
fmt = 'q'
newfmt = fmt
if fmt == 's':
newfmt = '%ds' % min(size, len(raw_bytes))
elif fmt in set(['number', 'datetime', 'date', 'time']):
newfmt = 'd'
if len(raw_bytes) != size:
size = len(raw_bytes)
if size < 8:
if self.endianess == 'little':
raw_bytes = b''.join([b'\x00' * (8 - size), raw_bytes])
else:
raw_bytes += b'\x00' * (8 - size)
size = 8
if self.endianess == 'big':
newfmt = '>%s' % newfmt
else:
newfmt = '<%s' % newfmt
val = struct.unpack(str(newfmt), raw_bytes[:size])[0]
if fmt == 's':
val = val.strip(b'\x00').strip()
elif math.isnan(val):
val = ''
elif fmt == 'datetime':
val = datetime(1960, 1, 1) + timedelta(seconds=val)
elif fmt == 'time':
val = (datetime(1960, 1, 1) + timedelta(seconds=val)).time()
elif fmt == 'date':
val = (datetime(1960, 1, 1) + timedelta(days=val)).date()
elif fmt in set(['number']):
i = int(val)
if i == val:
val = i
return val
def readlines(self):
"""
readlines() -> generator which yields lists of values, each a line
from the file.
Possible values in the list are None, string, float, datetime.datetime,
datetime.date, and datetime.time.
"""
bit_offset = self.header.PAGE_BIT_OFFSET
subheader_pointer_length = self.header.SUBHEADER_POINTER_LENGTH
row_count = self.header.properties.row_count
current_row_in_file_index = 0
current_row_on_page_index = 0
if not self.skip_header:
yield [x.name.decode(self.encoding, self.encoding_errors)
for x in self.columns]
if not self.cached_page:
self._file.seek(self.properties.header_length)
self._read_next_page()
while current_row_in_file_index < row_count:
current_row_in_file_index += 1
current_page_type = self.current_page_type
if current_page_type == self.header.PAGE_META_TYPE:
try:
current_subheader_pointer =\
self.current_page_data_subheader_pointers[
current_row_on_page_index
]
except IndexError:
self._read_next_page()
current_row_on_page_index = 0
else:
current_row_on_page_index += 1
cls = self.header.SUBHEADER_INDEX_TO_CLASS.get(
self.header.DATA_SUBHEADER_INDEX
)
if cls is None:
raise NotImplementedError
cls(self).process_subheader(
current_subheader_pointer.offset,
current_subheader_pointer.length
)
if current_row_on_page_index ==\
len(self.current_page_data_subheader_pointers):
self._read_next_page()
current_row_on_page_index = 0
elif current_page_type in self.header.PAGE_MIX_TYPE:
if self.align_correction:
align_correction = (
bit_offset + self.header.SUBHEADER_POINTERS_OFFSET +
self.current_page_subheaders_count *
subheader_pointer_length
) % 8
else:
align_correction = 0
offset = (
bit_offset + self.header.SUBHEADER_POINTERS_OFFSET +
align_correction + self.current_page_subheaders_count *
subheader_pointer_length + current_row_on_page_index *
self.properties.row_length
)
try:
self.current_row = self._process_byte_array_with_data(
offset,
self.properties.row_length
)
except:
self.logger.exception(
'failed to process data (you might want to try '
'passing align_correction=%s to the SAS7BDAT '
'constructor)' % (not self.align_correction)
)
raise
current_row_on_page_index += 1
if current_row_on_page_index == min(
self.properties.row_count,
self.properties.mix_page_row_count
):
self._read_next_page()
current_row_on_page_index = 0
elif current_page_type == self.header.PAGE_DATA_TYPE:
self.current_row = self._process_byte_array_with_data(
bit_offset + self.header.SUBHEADER_POINTERS_OFFSET +
current_row_on_page_index *
self.properties.row_length,
self.properties.row_length
)
current_row_on_page_index += 1
if current_row_on_page_index == self.current_page_block_count:
self._read_next_page()
current_row_on_page_index = 0
else:
self.logger.error('unknown page type: %s', current_page_type)
yield self.current_row
def _read_next_page(self):
self.current_page_data_subheader_pointers = []
self.cached_page = self._file.read(self.properties.page_length)
if len(self.cached_page) <= 0:
return
if len(self.cached_page) != self.properties.page_length:
self.logger.error(
'failed to read complete page from file (read %s of %s bytes)',
len(self.cached_page), self.properties.page_length
)
self.header.read_page_header()
if self.current_page_type == self.header.PAGE_META_TYPE:
self.header.process_page_metadata()
if self.current_page_type not in [
self.header.PAGE_META_TYPE,
self.header.PAGE_DATA_TYPE
] + self.header.PAGE_MIX_TYPE:
self._read_next_page()
def _process_byte_array_with_data(self, offset, length):
row_elements = []
if self.properties.compression and length < self.properties.row_length:
decompressor = self.DECOMPRESSORS.get(
self.properties.compression
)
source = decompressor(self).decompress_row(
offset, length, self.properties.row_length,
self.cached_page
)
offset = 0
else:
source = self.cached_page
for i in xrange(self.properties.column_count):
length = self.column_data_lengths[i]
if length == 0:
break
start = offset + self.column_data_offsets[i]
end = offset + self.column_data_offsets[i] + length
temp = source[start:end]
if self.columns[i].type == 'number':
if self.column_data_lengths[i] <= 2:
row_elements.append(self._read_val(
'h', temp, length
))
else:
fmt = self.columns[i].format
if not fmt:
row_elements.append(self._read_val(
'number', temp, length
))
elif fmt in self.TIME_FORMAT_STRINGS:
row_elements.append(self._read_val(
'time', temp, length
))
elif fmt in self.DATE_TIME_FORMAT_STRINGS:
row_elements.append(self._read_val(
'datetime', temp, length
))
elif fmt in self.DATE_FORMAT_STRINGS:
row_elements.append(self._read_val(
'date', temp, length
))
else:
row_elements.append(self._read_val(
'number', temp, length
))
else: # string
row_elements.append(self._read_val(
's', temp, length
).decode(self.encoding, self.encoding_errors))
return row_elements
def convert_file(self, out_file, delimiter=',', step_size=100000):
"""
convert_file(out_file[, delimiter[, step_size]]) -> None
A convenience method to convert a SAS7BDAT file into a delimited
text file. Defaults to comma separated. The step_size parameter
is uses to show progress on longer running conversions.
"""
delimiter = str(delimiter)
self.logger.debug('saving as: %s', out_file)
out_f = None
success = True
try:
if out_file == '-':
out_f = sys.stdout
else:
out_f = open(out_file, 'w')
out = csv.writer(out_f, lineterminator='\n', delimiter=delimiter)
i = 0
for i, line in enumerate(self, 1):
if len(line) != (self.properties.column_count or 0):
msg = 'parsed line into %s columns but was ' \
'expecting %s.\n%s' %\
(len(line), self.properties.column_count, line)
self.logger.error(msg)
success = False
if self.logger.level == logging.DEBUG:
raise ParseError(msg)
break
if not i % step_size:
self.logger.info(
'%.1f%% complete',
float(i) / self.properties.row_count * 100.0
)
try:
out.writerow(line)
except IOError:
self.logger.warn('wrote %s lines before interruption', i)
break
self.logger.info(u'\u27f6 [%s] wrote %s of %s lines',
os.path.basename(out_file), i - 1,
self.properties.row_count or 0)
finally:
if out_f is not None:
out_f.close()
return success
def to_data_frame(self):
"""
to_data_frame() -> pandas.DataFrame object
A convenience method to convert a SAS7BDAT file into a pandas
DataFrame.
"""
import pandas as pd
data = list(self.readlines())
return pd.DataFrame([dict(list(zip(data[0], x))) for x in data[1:]])
class Column(object):
def __init__(self, col_id, name, label, col_format, col_type, length):
self.col_id = col_id
self.name = name
self.label = label
self.format = col_format.decode("utf-8")
self.type = col_type
self.length = length
def __repr__(self):
return self.name
class SubheaderPointer(object):
def __init__(self, offset=None, length=None, compression=None,
p_type=None):
self.offset = offset
self.length = length
self.compression = compression
self.type = p_type
class ProcessingSubheader(object):
TEXT_BLOCK_SIZE_LENGTH = 2
ROW_LENGTH_OFFSET_MULTIPLIER = 5
ROW_COUNT_OFFSET_MULTIPLIER = 6
COL_COUNT_P1_MULTIPLIER = 9
COL_COUNT_P2_MULTIPLIER = 10
ROW_COUNT_ON_MIX_PAGE_OFFSET_MULTIPLIER = 15 # rowcountfp
COLUMN_NAME_POINTER_LENGTH = 8
COLUMN_NAME_TEXT_SUBHEADER_OFFSET = 0
COLUMN_NAME_TEXT_SUBHEADER_LENGTH = 2
COLUMN_NAME_OFFSET_OFFSET = 2
COLUMN_NAME_OFFSET_LENGTH = 2
COLUMN_NAME_LENGTH_OFFSET = 4
COLUMN_NAME_LENGTH_LENGTH = 2
COLUMN_DATA_OFFSET_OFFSET = 8
COLUMN_DATA_LENGTH_OFFSET = 8
COLUMN_DATA_LENGTH_LENGTH = 4
COLUMN_TYPE_OFFSET = 14
COLUMN_TYPE_LENGTH = 1
COLUMN_FORMAT_TEXT_SUBHEADER_INDEX_OFFSET = 22
COLUMN_FORMAT_TEXT_SUBHEADER_INDEX_LENGTH = 2
COLUMN_FORMAT_OFFSET_OFFSET = 24
COLUMN_FORMAT_OFFSET_LENGTH = 2
COLUMN_FORMAT_LENGTH_OFFSET = 26
COLUMN_FORMAT_LENGTH_LENGTH = 2
COLUMN_LABEL_TEXT_SUBHEADER_INDEX_OFFSET = 28
COLUMN_LABEL_TEXT_SUBHEADER_INDEX_LENGTH = 2
COLUMN_LABEL_OFFSET_OFFSET = 30
COLUMN_LABEL_OFFSET_LENGTH = 2
COLUMN_LABEL_LENGTH_OFFSET = 32
COLUMN_LABEL_LENGTH_LENGTH = 2
def __init__(self, parent):
self.parent = parent
self.logger = parent.logger
self.properties = parent.header.properties
self.int_length = 8 if self.properties.u64 else 4
def process_subheader(self, offset, length):
raise NotImplementedError
class RowSizeSubheader(ProcessingSubheader):
def process_subheader(self, offset, length):
int_len = self.int_length
lcs = offset + (682 if self.properties.u64 else 354)
lcp = offset + (706 if self.properties.u64 else 378)
vals = self.parent._read_bytes({
offset + self.ROW_LENGTH_OFFSET_MULTIPLIER * int_len: int_len,
offset + self.ROW_COUNT_OFFSET_MULTIPLIER * int_len: int_len,
offset + self.ROW_COUNT_ON_MIX_PAGE_OFFSET_MULTIPLIER * int_len:
int_len,
offset + self.COL_COUNT_P1_MULTIPLIER * int_len: int_len,
offset + self.COL_COUNT_P2_MULTIPLIER * int_len: int_len,
lcs: 2,
lcp: 2,
})
if self.properties.row_length is not None:
self.logger.error('found more than one row length subheader')
if self.properties.row_count is not None:
self.logger.error('found more than one row count subheader')
if self.properties.col_count_p1 is not None:
self.logger.error('found more than one col count p1 subheader')
if self.properties.col_count_p2 is not None:
self.logger.error('found more than one col count p2 subheader')
if self.properties.mix_page_row_count is not None:
self.logger.error('found more than one mix page row count '
'subheader')
self.properties.row_length = self.parent._read_val(
'i',
vals[offset + self.ROW_LENGTH_OFFSET_MULTIPLIER * int_len],
int_len
)
self.properties.row_count = self.parent._read_val(
'i',
vals[offset + self.ROW_COUNT_OFFSET_MULTIPLIER * int_len],
int_len
)
self.properties.col_count_p1 = self.parent._read_val(
'i',
vals[offset + self.COL_COUNT_P1_MULTIPLIER * int_len],
int_len
)
self.properties.col_count_p2 = self.parent._read_val(
'i',
vals[offset + self.COL_COUNT_P2_MULTIPLIER * int_len],
int_len
)
self.properties.mix_page_row_count = self.parent._read_val(
'i',
vals[offset + self.ROW_COUNT_ON_MIX_PAGE_OFFSET_MULTIPLIER *
int_len],
int_len
)
self.properties.lcs = self.parent._read_val('h', vals[lcs], 2)
self.properties.lcp = self.parent._read_val('h', vals[lcp], 2)
class ColumnSizeSubheader(ProcessingSubheader):
def process_subheader(self, offset, length):
offset += self.int_length
vals = self.parent._read_bytes({
offset: self.int_length
})
if self.properties.column_count is not None:
self.logger.error('found more than one column count subheader')
self.properties.column_count = self.parent._read_val(
'i', vals[offset], self.int_length
)
if self.properties.col_count_p1 + self.properties.col_count_p2 !=\
self.properties.column_count:
self.logger.warning('column count mismatch')
class SubheaderCountsSubheader(ProcessingSubheader):
def process_subheader(self, offset, length):
pass # Not sure what to do here yet
class ColumnTextSubheader(ProcessingSubheader):
def process_subheader(self, offset, length):
offset += self.int_length
vals = self.parent._read_bytes({
offset: self.TEXT_BLOCK_SIZE_LENGTH
})
text_block_size = self.parent._read_val(
'h', vals[offset], self.TEXT_BLOCK_SIZE_LENGTH
)
vals = self.parent._read_bytes({
offset: text_block_size
})
self.parent.column_names_strings.append(vals[offset])
if len(self.parent.column_names_strings) == 1:
column_name = self.parent.column_names_strings[0]
compression_literal = None
for cl in SAS7BDAT.COMPRESSION_LITERALS:
if cl in column_name:
compression_literal = cl
break
self.properties.compression = compression_literal
offset -= self.int_length
vals = self.parent._read_bytes({
offset + (20 if self.properties.u64 else 16): 8
})
compression_literal = self.parent._read_val(
's',
vals[offset + (20 if self.properties.u64 else 16)],
8
).strip()
if compression_literal == '':
self.properties.lcs = 0
vals = self.parent._read_bytes({
offset + 16 + (20 if self.properties.u64 else 16):
self.properties.lcp
})
creatorproc = self.parent._read_val(
's',
vals[offset + 16 + (20 if self.properties.u64 else 16)],
self.properties.lcp
)
self.properties.creator_proc = creatorproc
elif compression_literal == SAS7BDAT.RLE_COMPRESSION:
vals = self.parent._read_bytes({
offset + 24 + (20 if self.properties.u64 else 16):
self.properties.lcp
})
creatorproc = self.parent._read_val(
's',
vals[offset + 24 + (20 if self.properties.u64 else 16)],
self.properties.lcp
)
self.properties.creator_proc = creatorproc
elif self.properties.lcs > 0:
self.properties.lcp = 0
vals = self.parent._read_bytes({
offset + (20 if self.properties.u64 else 16):
self.properties.lcs
})
creator = self.parent._read_val(
's',
vals[offset + (20 if self.properties.u64 else 16)],
self.properties.lcs
)
self.properties.creator = creator