For programmers! Use SAS procedures, Python, Lua, REST APIs, and more!

How to display Python code in SAS communities

Community Manager
Posts: 3,099

How to display Python code in SAS communities

[ Edited ]

There isn't special "insert Python code" button like we have for SAS code, but we can use the same mechanism to add Python code -- if we add one small step.


To add Python code to your post:


  1. Click the SAS code button (running man icon).  The Insert SAS code window appears.
  2. Type or paste your Python code, then click OK.
  3. In the message editor, switch from Rich Text to HTML view.
  4. Change the <code language="language-sas"> tag to <code language="language-python">
  5. Don't visit the Preview tab, which can re-write some of the HTML and lose formatting.  You won't see the Python coloring while you edit the message, but it will appear properly when the message is posted.


If you need to edit the message later, you can still use the "running man" icon to invoke the code edit window -- the "language-python" attribute should remain as it is.


Here's an example of the result:


import argparse

# Default host information
host = ""
port = 19990

# Parse the command-line input
parser = argparse.ArgumentParser()
parser.add_argument("--host", help="CAS host name", default=host)
parser.add_argument("--port", help="CAS host port", type=int, default=port)
args = parser.parse_args()
host =
port = args.port

# Begin script
print(">> Starting Python CAS Client example.")

# Load the SWAT package
    from swat import *
except ImportError as err:
    print("Failed to load SWAT package:", err)
print(">> Loaded the SWAT package.")

# Connect to the CAS server
    s = CAS(host, port)
except Exception as err:
print(">> Connected to host ", host, " on port ", port, ".", sep="")

# Set the CASLIB to HPS
rc = s.setsessopt(caslib="hps")
if rc.severity != 0:

# Load Table Cars_Data
rc = s.loadtable(path="cars_data.sashdat")
if rc.severity != 0:
print(">> Loaded table Cars_Data.")

# Summarize variable Mpg_Mileage in table Cars_Data, and group results by variable Type.
res = s.summary(multitable=False, table={"groupBy":{"Type"},
  "casLib":"HPS", "name":"cars_data", "varList":[{"name":"mpg_highway"}]})
if res.severity != 0:
print(">> Summarized variable Mpg_Highway in table Cars_Data and grouped by variable Type.")

# Extract the summary data from the results
summ = res['Summary']

# Print the summary results
print(">> Summary results:")
from pprint import pprint
pprint(summ.loc[:, ['Type', 'Mean', 'Min', 'Max']])

# Close the client connection
print(">> Closed client connection.")



Ask a Question
Discussion stats
  • 0 replies
  • 1 in conversation