How to run Python through SAS?

Perhaps you have already encountered situations when you have a program written in python (there can be many such programs and they can be written by your colleagues) and you need to embed this run in the SAS program code.

How to do this?



So, for this we will use the following open-source tool with github . First, copy the SASJavaExec.java file to yourself and compile it into a jar file. An important point: you must compile with JDK 1.7_025, because when using JDK 1.8, an error will occur in the SAS code.

1. Create classes: java -jar SASJavaExec.jar
2. Compile into jar file: jar cfm SASJavaExec.jar manifest.txt SASJavaExec $ 1.class SASJavaExec.class

Where manifest.txt is a one-line file: Main-Class: SASJavaExec. Now we have the SASJavaExec.jar file.

Next, you need to register it in the system settings. I ran the program on Windows, so I need to set the CLASSPATH variable in the environment settings.

In my case, it looked like this:


More details on how to do this can be found here .

After you have done all the above steps, run SAS.

The following paths must be specified:

Python file path:% let PYTHON_EXEC_COMMAND = C: \ Python27 \ python.exe;
The path to your python program:

%let WORK_DIR = C:\SAS\T_Java\Example;	
python_pgm = "&WORK_DIR.\digitsdata_svm.py";

After that, we write the executable code - Data set:

/*** Part I: Python ***/
data _null_;
  length rtn_val 8;
  *** Python program takes working directory as first argument;
  python_pgm = "&WORK_DIR.\digitsdata_svm.py";
  python_arg1 = "&WORK_DIR";      
  python_call = cat('"', trim(python_pgm), '" "', trim(python_arg1), '"'); 
  put python_pgm = ;
  put python_arg1 =;
  put python_call=;
  declare javaobj j("SASJavaExec", "&PYTHON_EXEC_COMMAND", python_call); 
  j.callIntMethod("executeProcess", rtn_val);
run;

Next, run our program and see the execution log:

python_pgm=C:\SAS\T_Java\Example\digitsdata_svm.py
python_arg1=C:\SAS\T_Java\Example
python_call="C:\SAS\T_Java\Example\digitsdata_svm.py" "C:\SAS\T_Java\Example"
27, 2016 6:36:39 AM SASJavaExec executeProcess
INFO: Executing [C:\Python27\python.exe, C:\SAS\T_Java\Example\digitsdata_svm.py, C:\SAS\T_Java\Example] ...
27, 2016 6:36:39 AM SASJavaExec executeProcess
INFO: Starting external process ...
 27, 2016 6:36:39 AM SASJavaExec executeProcess
INFO: External process exit value 0.

Everything is in order, the digitsdata_svm.py program was executed from SAS.

I hope this article was useful to you.

PS An example of the SAS program itself was also taken from github, the link to which was indicated at the beginning of the article.

Also popular now: