/
sasbase.py
2149 lines (1845 loc) · 80.8 KB
/
sasbase.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
#
# Copyright SAS Institute
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
# This module is designed to connect to SAS from python, providing a natural python style interface.
# it provides base functionality, data access and processing, and includes analytics and ODS results.
# There is a configuration file named sascfg.py in the saspy package used to configure connections
# to SAS. Currently supported methods are STDIO, connecting to a local (same machine) Linux SAS using
# stdio methods (fork, exec, and pipes). The is also support for running STDIO over SSH, which can
# connect to a remote linux SAS via passwordless ssh. The ssh method cannot currently support interrupt
# handling, as the local STDIO method can. An interrupt on this method can only terminate the SAS process;
# you'll be prompted to terminate or wait for completion. The third method is HTTP, which can connect
# to SAS Viya via the Compute Service, a restful micro service in the Viya system.
#
# Each of these connection methods (access methods) are handled by their own IO module. This main
# module determines which IO module to use based upon the configuration chosen at runtime. More
# IO modules can be seamlessly plugged in, if needed, in the future.
#
# The expected use is to simply import this package and establish a SAS session, then use the methods:
#
# import saspy
# sas = saspy.SASsession()
# sas.[have_at_it]()
#
import os
import sys
import re
# from pdb import set_trace as bp
import logging
try:
import pandas as pd
except ImportError:
pass
try:
import saspy.sascfg_personal as SAScfg
except ImportError:
try:
import sascfg_personal as SAScfg
except ImportError:
import saspy.sascfg as SAScfg
try:
import saspy.sasiostdio as sasiostdio
except:
pass
import saspy.sasioiom as sasioiom
#import saspy.sasiohttp as sasiohttp
from saspy.sasstat import *
from saspy.sasets import *
from saspy.sasml import *
from saspy.sasqc import *
from saspy.sasutil import *
from saspy.sasresults import *
from saspy.sastabulate import Tabulate
try:
from IPython.display import HTML
from IPython.display import display as DISPLAY
except ImportError:
pass
class SASconfig:
"""
This object is not intended to be used directly. Instantiate a SASsession object instead
"""
def __init__(self, **kwargs):
configs = []
self._kernel = kwargs.get('kernel', None)
self.valid = True
self.mode = ''
# GET Config options
try:
self.cfgopts = getattr(SAScfg, "SAS_config_options")
except:
self.cfgopts = {}
# GET Config names
configs = getattr(SAScfg, "SAS_config_names")
cfgname = kwargs.get('cfgname', '')
if len(cfgname) == 0:
if len(configs) == 0:
print("No SAS Configuration names found in saspy.sascfg")
self.valid = False
return
else:
if len(configs) == 1:
cfgname = configs[0]
if self._kernel is None:
print("Using SAS Config named: " + cfgname)
else:
cfgname = self._prompt(
"Please enter the name of the SAS Config you wish to run. Available Configs are: " +
str(configs) + " ")
while cfgname not in configs:
cfgname = self._prompt(
"The SAS Config name specified was not found. Please enter the SAS Config you wish to use. Available Configs are: " +
str(configs) + " ")
if cfgname is None:
raise KeyboardInterrupt
self.name = cfgname
cfg = getattr(SAScfg, cfgname)
ip = cfg.get('ip', '')
ssh = cfg.get('ssh', '')
path = cfg.get('saspath', '')
java = cfg.get('java', '')
self.results = cfg.get('results', None)
if len(java) > 0:
self.mode = 'IOM'
elif len(ip) > 0:
self.mode = 'HTTP'
elif len(ssh) > 0:
self.mode = 'SSH'
elif len(path) > 0:
self.mode = 'STDIO'
else:
print("Configuration Definition "+cfgname+" is not valid. Failed to create a SASsession.")
self.valid = False
def _prompt(self, prompt, pw=False):
if self._kernel is None:
if not pw:
try:
return input(prompt)
except KeyboardInterrupt:
return None
else:
try:
return getpass.getpass(prompt)
except KeyboardInterrupt:
return None
else:
try:
return self._kernel._input_request(prompt, self._kernel._parent_ident, self._kernel._parent_header,
password=pw)
except KeyboardInterrupt:
return None
class SASsession():
"""
**Overview**
The SASsession object is the main object to instantiate and provides access to the rest of the functionality.
Most of these parameters will be configured in the sascfg.py configuration file.
Common parms for all access methods are:
:param cfgname: value in SAS_config_names List of the sascfg.py file
:param kernel: None - internal use when running the SAS_kernel notebook
:param results: Type of tabular results to return. default is 'Pandas', other options are 'HTML or 'TEXT'
:return: 'SASsession'
:rtype: 'SASsession'
And each access method has its own set of parameters.
**STDIO**
:param saspath: overrides saspath Dict entry of cfgname in sascfg.py file
:param options: overrides options Dict entry of cfgname in sascfg.py file
:param encoding: This is the python encoding value that matches the SAS session encoding
**STDIO over SSH**
and for running STDIO over passwordless ssh, add these required parameters
:param ssh: full path of the ssh command; /usr/bin/ssh for instance
:param host: host name of the remote machine
**IOM**
and for the IOM IO module to connect to SAS9 via Java IOM
:param java: the path to the java executable to use
:param iomhost: for remote IOM case, not local Windows] the resolvable host name, or ip to the IOM server to connect to
:param iomport: for remote IOM case, not local Windows] the port IOM is listening on
:param omruser: user id for remote IOM access
:param omrpw: pw for user for remote IOM access
:param encoding: This is the python encoding value that matches the SAS session encoding of the IOM server you are connecting to
:param classpath: classpath to IOM client jars and saspyiom client jar.
"""
# def __init__(self, cfgname: str ='', kernel: 'SAS_kernel' =None, saspath :str ='', options: list =[]) -> 'SASsession':
def __init__(self, **kwargs) -> 'SASsession':
self._loaded_macros = False
self._obj_cnt = 0
self.nosub = False
self.sascfg = SASconfig(**kwargs)
self.batch = False
self.results = kwargs.get('results', self.sascfg.results)
if not self.results:
self.results = 'Pandas'
self.workpath = ''
self.sasver = ''
self.sascei = ''
if not self.sascfg.valid:
self._io = None
return
if self.sascfg.mode in ['STDIO', 'SSH', '']:
if os.name != 'nt':
self._io = sasiostdio.SASsessionSTDIO(sascfgname=self.sascfg.name, sb=self, **kwargs)
else:
print(
"Cannot use STDIO I/O module on Windows. No SASsession established. Choose an IOM SASconfig definition")
elif self.sascfg.mode == 'IOM':
self._io = sasioiom.SASsessionIOM(sascfgname=self.sascfg.name, sb=self, **kwargs)
'''
elif self.sascfg.mode == 'HTTP':
self._io = sasiohttp.SASsessionHTTP(sascfgname=self.sascfg.name, sb=self, **kwargs)
'''
try:
if self._io:
ll = self.submit('libname work list;')
self.workpath = ll['LOG'].partition('Physical Name=')[2].partition('\n')[0].strip()
win = self.workpath.count('\\')
lnx = self.workpath.count('/')
if (win > lnx):
self.workpath += '\\'
else:
self.workpath += '/'
ll = self.submit('%put SYSV=&sysvlong4;')
self.sasver = ll['LOG'].rpartition('SYSV=')[2].partition('\n')[0].strip()
ll = self.submit('proc options option=encoding;run;')
self.sascei = ll['LOG'].rpartition('ENCODING=')[2].partition(' ')[0].strip()
except (AttributeError):
self._io = None
def __repr__(self):
"""
display info about this object ...
:return: output
"""
if self._io is None:
return "This SASsession object is not valid\n"
x = "Access Method = %s\n" % self.sascfg.mode
x += "SAS Config name = %s\n" % self.sascfg.name
x += "WORK Path = %s\n" % self.workpath
x += "SAS Version = %s\n" % self.sasver
x += "SASPy Version = %s\n" % sys.modules['saspy'].__version__
x += "Teach me SAS = %s\n" % str(self.nosub)
x += "Batch = %s\n" % str(self.batch)
x += "Results = %s\n" % self.results
x += "SAS Session Encoding = %s\n" % self.sascei
x += "Python Encoding value = %s\n" % self._io.sascfg.encoding
return(x)
def __del__(self):
if self._io:
if self._io:
return self._io.__del__()
def _objcnt(self):
self._obj_cnt += 1
return '%04d' % self._obj_cnt
def _startsas(self):
return self._io._startsas()
def _endsas(self):
return self._io._endsas()
def _getlog(self, **kwargs):
return self._io._getlog(**kwargs)
def _getlst(self, **kwargs):
return self._io._getlst(**kwargs)
def _getlsttxt(self, **kwargs):
return self._io._getlsttxt(**kwargs)
def _asubmit(self, code, results):
if results == '':
if self.results.upper() == 'PANDAS':
results = 'HTML'
else:
results = self.results
return self._io._asubmit(code, results)
def submit(self, code: str, results: str = '', prompt: dict = []) -> dict:
'''
This method is used to submit any SAS code. It returns the Log and Listing as a python dictionary.
- code - the SAS statements you want to execute
- results - format of results, HTLML and TEXT is the alternative
- prompt - dict of names:flags to prompt for; create macro variables (used in submitted code), then keep or delete
the keys which are the names of the macro variables. The boolean flag is to either hide what you type and delete the macros,
or show what you type and keep the macros (they will still be available later).
for example (what you type for pw will not be displayed, user and dsname will):
.. code-block:: python
results_dict = sas.submit(
"""
libname tera teradata server=teracop1 user=&user pw=&pw;
proc print data=tera.&dsname (obs=10); run;
""" ,
prompt = {'user': False, 'pw': True, 'dsname': False}
)
Returns - a Dict containing two keys:values, [LOG, LST]. LOG is text and LST is 'results' (HTML or TEXT)
NOTE: to view HTML results in the ipykernel, issue: from IPython.display import HTML and use HTML() instead of print()
i.e,: results = sas.submit("data a; x=1; run; proc print;run')
print(results['LOG'])
HTML(results['LST'])
'''
if self.nosub:
return dict(LOG=code, LST='')
if results == '':
if self.results.upper() == 'PANDAS':
results = 'HTML'
else:
results = self.results
return self._io.submit(code, results, prompt)
def saslog(self) -> str:
"""
This method is used to get the current, full contents of the SASLOG
:return: SAS log
:rtype: str
"""
return self._io.saslog()
def teach_me_SAS(self, nosub: bool):
'''
nosub - bool. True means don't submit the code, print it out so I can see what the SAS code would be.
False means run normally - submit the code.
'''
self.nosub = nosub
def set_batch(self, batch: bool) -> bool:
"""
This method sets the batch attribute for the SASsession object; it stays in effect until changed.
For methods that just display results like SASdata object methods (head, tail, hist, series, etc.)
and SASresult object results, you can set 'batch' to true to get the results back directly so you
can write them to files or whatever you want to do with them.
This is intended for use in python batch scripts so you can still get ODS XML5 results
and save them to files, which you couldn't otherwise do for these methods.
When running interactively, the expectation is that you want to have the results directly rendered,
but you can run this way too; get the objects display them yourself and/or write them to somewhere.
When `set_batch ==True`, you get the same dictionary returned as from the `SASsession.submit()` method.
:param batch: bool
:rtype: bool
:return: True = return dict([LOG, LST]. False = display LST to screen.
"""
self.batch = batch
def set_results(self, results: str) -> str:
"""
This method set the results attribute for the SASsession object; it stays in effect till changed
:param results: set the default result type for this SASdata object. ``'Pandas' or 'HTML' or 'TEXT'``.
:return: string of the return type
:rtype: str
"""
self.results = results
def exist(self, table: str, libref: str = "") -> bool:
"""
Does the SAS data set currently exist
:param table: the name of the SAS Data Set
:param libref: the libref for the Data Set, defaults to WORK, or USER if assigned
:return: Boolean True it the Data Set exists and False if it does not
:rtype: bool
"""
return self._io.exist(table, libref)
def sasets(self) -> 'SASets':
"""
This methods creates a SASets object which you can use to run various analytics.
See the sasets.py module.
:return: sasets object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASets(self)
def sasstat(self) -> 'SASstat':
"""
This methods creates a SASstat object which you can use to run various analytics.
See the sasstat.py module.
:return: sasstat object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASstat(self)
def sasml(self) -> 'SASml':
"""
This methods creates a SASML object which you can use to run various analytics. See the sasml.py module.
:return: sasml object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASml(self)
def sasqc(self) -> 'SASqc':
"""
This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module.
:return: sasqc object
"""
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASqc(self)
def sasutil(self) -> 'SASutil':
'''
This methods creates a SASutil object which you can use to run various analytics.
See the sasutil.py module.
:return: sasutil object
'''
if not self._loaded_macros:
self._loadmacros()
self._loaded_macros = True
return SASutil(self)
def _loadmacros(self):
"""
Load the SAS macros at the start of the session
:return:
"""
macro_path = os.path.dirname(os.path.realpath(__file__))
fd = os.open(macro_path + '/' + 'libname_gen.sas', os.O_RDONLY)
code = b'options nosource;\n'
code += os.read(fd, 32767)
code += b'\noptions source;'
self._io._asubmit(code.decode(), results='text')
os.close(fd)
def sasdata(self, table: str, libref: str = '', results: str = '', dsopts: dict = {}) -> 'SASdata':
"""
Method to define an existing SAS dataset so that it can be accessed via SASPy
:param table: the name of the SAS Data Set
:param libref: the libref for the Data Set, defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, Pandas, HTML and TEXT are the valid options
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
}
:return: SASdata object
"""
if results == '':
results = self.results
sd = SASdata(self, libref, table, results, dsopts)
if not self.exist(sd.table, sd.libref):
if not self.batch:
print(
"Table " + sd.libref + '.' + sd.table + " does not exist. This SASdata object will not be useful until the data set is created.")
return sd
def saslib(self, libref: str, engine: str = ' ', path: str = '',
options: str = ' ', prompt: dict = []) -> str:
"""
:param libref: the libref to be assigned
:param engine: the engine name used to access the SAS Library (engine defaults to BASE, per SAS)
:param path: path to the library (for engines that take a path parameter)
:param options: other engine or engine supervisor options
:return: SAS log
"""
code = "libname " + libref + " " + engine + " "
if len(path) > 0:
code += " '" + path + "' "
code += options + ";"
if self.nosub:
print(code)
else:
ll = self._io.submit(code, "text", prompt)
if self.batch:
return ll['LOG'].rsplit(";*\';*\";*/;\n")[0]
else:
print(ll['LOG'].rsplit(";*\';*\";*/;\n")[0])
def datasets(self, libref: str = '') -> str:
"""
This method is used to query a libref. The results show information about the libref including members.
:param libref: the libref to query
:return:
"""
code = "proc datasets"
if libref:
code += " dd=" + libref
code += "; quit;"
if self.nosub:
print(code)
else:
ll = self._io.submit(code, "text")
if self.batch:
return ll['LOG'].rsplit(";*\';*\";*/;\n")[0]
else:
print(ll['LOG'].rsplit(";*\';*\";*/;\n")[0])
def read_csv(self, file: str, table: str = '_csv', libref: str = '', results: str = '', opts: dict ={}) -> 'SASdata':
"""
:param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:param opts: a dictionary containing any of the following Proc Import options(datarow, delimiter, getnames, guessingrows)
:return: SASdata object
"""
if results == '':
results = self.results
self._io.read_csv(file, table, libref, self.nosub, opts)
if self.exist(table, libref):
return SASdata(self, libref, table, results)
else:
return None
def write_csv(self, file: str, table: str, libref: str = '',
dsopts: dict = {}, opts: dict ={}) -> str:
"""
:param file: the OS filesystem path of the file to be created (exported from the SAS Data Set)
:param table: the name of the SAS Data Set you want to export to a CSV file
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs)
:param opts: a dictionary containing any of the following Proc Export options(delimiter, putnames)
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
}
:return: SAS log
"""
log = self._io.write_csv(file, table, libref, self.nosub, dsopts, opts)
if not self.batch:
print(log)
else:
return log
def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '') -> 'SASdata':
"""
This is an alias for 'dataframe2sasdata'. Why type all that?
:param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:return: SASdata object
"""
return self.dataframe2sasdata(df, table, libref, results)
def dataframe2sasdata(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '',
results: str = '') -> 'SASdata':
"""
This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set.
:param df: Pandas Data Frame to import to a SAS Data Set
:param table: the name of the SAS Data Set to create
:param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:return: SASdata object
"""
if results == '':
results = self.results
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
self._io.dataframe2sasdata(df, table, libref)
if self.exist(table, libref):
return SASdata(self, libref, table, results)
else:
return None
def sd2df(self, table: str, libref: str = '', dsopts: dict = {}, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame':
"""
This is an alias for 'sasdata2dataframe'. Why type all that?
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
}
:param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data
:param kwargs: dictionary
:return: Pandas data frame
"""
return self.sasdata2dataframe(table, libref, dsopts, method, **kwargs)
def sd2df_CSV(self, table: str, libref: str = '', dsopts: dict = {}, **kwargs) -> 'pd.DataFrame':
"""
This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that?
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
}
:param kwargs: dictionary
:return: Pandas data frame
"""
return self.sasdata2dataframe(table, libref, dsopts, method='CSV', **kwargs)
def sasdata2dataframe(self, table: str, libref: str = '', dsopts: dict = {}, method: str = 'MEMORY',
**kwargs) -> 'pd.DataFrame':
"""
This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object.
SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame
:param table: the name of the SAS Data Set you want to export to a Pandas Data Frame
:param libref: the libref for the SAS Data Set.
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
}
:param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data
:param kwargs: dictionary
:return: Pandas data frame
"""
if self.exist(table, libref) == 0:
print('The SAS Data Set ' + libref + '.' + table + ' does not exist')
return None
if self.nosub:
print("too complicated to show the code, read the source :), sorry.")
return None
else:
return self._io.sasdata2dataframe(table, libref, dsopts, method=method, **kwargs)
def _dsopts(self, dsopts):
"""
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string or list of strings
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
- format is a string or dictionary { var: format }
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"'
'keep' : 'msrp enginesize Cylinders Horsepower Weight'
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight']
'obs' : 10
'firstobs' : '12'
'format' : {'money': 'dollar10', 'time': 'tod5.'}
}
:return: str
"""
opts = ''
fmat = ''
if len(dsopts):
for key in dsopts:
if len(str(dsopts[key])):
if key == 'where':
if isinstance(dsopts[key], str):
opts += 'where=(' + dsopts[key] + ') '
elif isinstance(dsopts[key], list):
opts += 'where=(' + " and ".join(dsopts[key]) + ') '
else:
raise TypeError("Bad key type. {} must be a str or list type".format(key))
elif key == 'drop':
opts += 'drop='
if isinstance(dsopts[key], list):
for var in dsopts[key]:
opts += var + ' '
else:
opts += dsopts[key] + ' '
elif key == 'keep':
opts += 'keep='
if isinstance(dsopts[key], list):
for var in dsopts[key]:
opts += var + ' '
else:
opts += dsopts[key] + ' '
elif key == 'obs':
opts += 'obs=' + str(dsopts[key]) + ' '
elif key == 'firstobs':
opts += 'firstobs=' + str(dsopts[key]) + ' '
elif key == 'format':
if isinstance(dsopts[key], str):
fmat = 'format ' + dsopts[key] + ';'
elif isinstance(dsopts[key], dict):
fmat = 'format '
for k, v in dsopts[key].items():
fmat += ' '.join((k, v)) + ' '
fmat += ';'
else:
raise TypeError("Bad key type. {} must be a str or dict type".format(key))
if len(opts):
opts = '(' + opts + ')'
if len(fmat) > 0:
opts += ';\n\t' + fmat
elif len(fmat) > 0:
opts = ';' + fmat
return opts
def _impopts(self, opts):
"""
:param opts: a dictionary containing any of the following Proc Import options(datarow, delimiter, getnames, guessingrows):
- datarow is a number
- delimiter is a character
- getnames is a boolean
- guessingrows is a numbers or the string 'MAX'
.. code-block:: python
{'datarow' : 2
'delimiter' : ',''
'getnames' : True
'guessingrows': 20
}
:return: str
"""
optstr = ''
if len(opts):
for key in opts:
if len(str(opts[key])):
if key == 'datarow':
optstr += 'datarow=' + str(opts[key]) + ';'
elif key == 'delimiter':
optstr += 'delimiter='
optstr += "'"+'%02x' % ord(opts[key].encode(self._io.sascfg.encoding))+"'x; "
elif key == 'getnames':
optstr += 'getnames='
if opts[key]:
optstr += 'YES; '
else:
optstr += 'NO; '
elif key == 'guessingrows':
optstr += 'guessingrows='
if opts[key] == 'MAX':
optstr += 'MAX; '
else:
optstr += str(opts[key])+'; '
return optstr
def _expopts(self, opts):
"""
:param opts: a dictionary containing any of the following Proc Export options(delimiter, putnames):
- delimiter is a character
- putnames is a boolean
.. code-block:: python
{'delimiter' : ',''
'putnames' : True
}
:return: str
"""
optstr = ''
if len(opts):
for key in opts:
if len(str(opts[key])):
if key == 'delimiter':
optstr += 'delimiter='
optstr += "'"+'%02x' % ord(opts[key].encode(self._io.sascfg.encoding))+"'x; "
elif key == 'putnames':
optstr += 'putnames='
if opts[key]:
optstr += 'YES; '
else:
optstr += 'NO; '
return optstr
def symput(self, name, value):
"""
:param name: name of the macro varable to set:
:param value: python variable to use for the value to assign to the macro variable:
- name is a character
- value is a variable that can be resolved to a string
"""
ll = self.submit("%let "+name +"=%NRBQUOTE("+str(value)+");\n")
def symget(self, name):
"""
:param name: name of the macro varable to set:
- name is a character
"""
ll = self.submit("%put "+name+"=&"+name+";\n")
l2 = ll['LOG'].rpartition(name+"=")
l2 = l2[2].partition("\n")
try:
var = int(l2[0])
except:
try:
var = float(l2[0])
except:
var = l2[0]
return var
def disconnect(self):
"""
This method disconnects an IOM session to allow for reconnecting when switching networks
See the Advanced topics section of the doc for details
"""
if self.sascfg.mode != 'IOM':
res = "This method is only available with the IOM access method"
else:
res = self._io.disconnect()
return res
class SASdata:
def __init__(self, sassession, libref, table, results='', dsopts={}):
"""
:param sassession:
:param table: the name of the SAS Data Set
:param libref: the libref for the SAS Data Set.
:param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives
:param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs):
- where is a string
- keep are strings or list of strings.
- drop are strings or list of strings.
- obs is a numbers - either string or int
- first obs is a numbers - either string or int
.. code-block:: python
{'where' : 'msrp < 20000 and make = "Ford"',
'keep' : 'msrp enginesize Cylinders Horsepower Weight',
'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'],
'obs' : 10,
'firstobs' : '12'
}
end comment
"""
self.sas = sassession
self.logger = logging.getLogger(__name__)
if results == '':
results = sassession.results
failed = 0
if results.upper() == "HTML":
try:
from IPython.display import HTML
except:
failed = 1
if failed and not self.sas.batch:
self.HTML = 0
else:
self.HTML = 1
else:
self.HTML = 0
if len(libref):
self.libref = libref
else:
if self.sas.exist(table, libref='user'):
self.libref = 'USER'
else:
self.libref = 'WORK'
# hack till the bug gets fixed