SASpy
This page is dedicated to Tom Boardman, whose passion for SAS and knowledge sharing continues to inspire.
SASpy
This page demonstrates how to connect Python to SAS using the SASPy library. We will show how to configure the connection, establish a session, and submit SAS code from Python.
The following packages are required:
Package | Comment |
---|---|
saspy | Main Python library for connecting to SAS. |
pandas | For handling dataframes (optional, but common). |
Below is an example SASPy configuration block:
# The names of the SAS configurations to use
SAS_config_names = ["iomcom"]
# Configuration block for the IOM connection
iomcom = {
"iomhost": "your_sas_server_name_or_ip",
"iomport": 8591,
"iomuser": "your_username",
"iompwd": "your_password",
"provider": "sas.iomprovider"
}
# Configuration options applied globally to the SAS connection
SAS_config_options = {
"lock_down": True,
"verbose": True
}
After defining parameters, you can establish a connection and submit SAS code. Here is a class-based example:
import saspy
class SASSession:
def __init__(self):
"""Initializes the SAS session using the predefined configuration."""
self.sas = None
self._initialize_session()
def _initialize_session(self):
try:
self.sas = saspy.SASsession()
print("SAS session initialized successfully.")
except Exception as e:
print(f"Error initializing SAS session: {e}")
self.sas = None
def submit(self, sas_code):
"""Submits SAS code to the session and returns the result."""
if self.sas:
result = self.sas.submit(sas_code)
sas_log = result.get('LOG', 'No LOG output')
sas_lst = result.get('LST', 'No LST output')
return {'LOG': sas_log, 'LST': sas_lst}
else:
print("SAS session is not initialized.")
return None
def close(self):
"""Closes the SAS session."""
if self.sas:
self.sas._endsas()
print("SAS session closed.")
else:
print("SAS session is not open.")
# Example usage
if __name__ == "__main__":
sas_session = SASSession()
result = sas_session.submit("proc print data=sashelp.class; run;")
if result:
print("SAS LOG:", result['LOG'])
print("SAS OUTPUT (LST):", result['LST'])
sas_session.close()
For more details, see the SASPy documentation.