SASPy (SAS Python Interface)

5.105.1 · active · verified Thu Apr 16

SASPy is an open-source Python package that provides an interface to the SAS System, allowing Python programmers to leverage their licensed SAS infrastructure. It enables bi-directional data exchange between pandas DataFrames and SAS datasets, submission of SAS code, and access to SAS analytical capabilities like machine learning and econometrics. Currently at version 5.105.1, the library maintains an active release cadence with frequent updates addressing new features, enhancements, and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a SAS session, submit arbitrary SAS code, and exchange data between a pandas DataFrame and a SAS dataset. It highlights the importance of the `sascfg_personal.py` configuration file for defining SAS connection details.

import saspy
import pandas as pd
import os

# NOTE: SASPy requires a configuration file (sascfg_personal.py) to define connection details.
# This file is typically located in your Python site-packages/saspy directory or ~/.config/saspy/.
# For example, using a 'winlocal' configuration (defined in sascfg_personal.py):
# sas = saspy.SASsession(cfgname='winlocal')
# If only one configuration is defined, or if running in an interactive environment that supports prompts:
sas = saspy.SASsession()

print(f"SAS Connection established: {sas.SASsessionid}")

# Example: Submit SAS code and get results
result = sas.submit("proc print data=sashelp.class(obs=5); run;")
print("SAS Log:\n", result['LOG'])
print("SAS Listing:\n", result['LST'])

# Example: Transfer a pandas DataFrame to SAS
data_df = pd.DataFrame({
    'col1': [1, 2, 3],
    'col2': ['A', 'B', 'C']
})

sas_data_obj = sas.dataframe2sasdata(data_df, 'WORK.mydata')
print(f"DataFrame '{data_df.shape}' transferred to SAS library WORK as 'mydata'.")

# Example: Read SAS data back into a pandas DataFrame
retrieved_df = sas.sasdata('mydata', libref='WORK').to_dataframe()
print(f"Retrieved DataFrame head:\n{retrieved_df.head()}")

sas.endsas()

view raw JSON →