(Oct 2024) – SAS Programming – Various Methods to Call Python in SAS Code
To call Python code from SAS 9.4, you can use the PROC PYTHON procedure, which was introduced in SAS Viya. However, SAS 9.4 does not natively support running Python code within SAS as directly as Viya does.
For SAS 9.4, you'll need to use a workaround approach, such as calling Python scripts using the X command or %SYSEXEC. Here's how you can do it:
Option 1: Use the X Command or %SYSEXEC
You can run Python scripts by executing system commands from within SAS.
1. Create a Python Script (my_script.py)
# my_script.py
print("Hello from Python")2. Call the Python Script from SAS
/* Allow SAS to run system commands without waiting */
options noxwait noxsync;
/* Using the X command */
x "python my_script.py";
/* Alternatively, use %SYSEXEC */
%sysexec python my_script.py;Note: Make sure that Python is installed on the machine where SAS is running, and the Python executable is included in the system PATH.
Option 2: Use the FILENAME Statement with PIPE
If you need to capture the output of the Python script and use it within SAS, you can use the FILENAME statement with PIPE.
1. Run Python Script and Capture Output
filename python pipe 'python -c "print(\"Hello from Python\")"';
data _null_;
infile python;
input;
put _infile_; /* Print the output from the Python script */
run;This method can be used to pass data between SAS and Python by using standard input/output streams.
Option 3: Use PROC GROOVY
PROC GROOVY allows for some scripting capability but is intended for Java. If your Python script is relatively simple, you could rewrite it in Java or use Jython (Python implementation for the Java platform). However, this is less straightforward than the other methods.
Additional Notes
- Make sure the Python path is correctly set up on your system.
- The X command and %SYSEXEC may require appropriate permissions in your SAS environment.
- For more complex integration, consider using SAS Viya, which has much better native support for Python through PROC PYTHON.