SPSS Statistics

 View Only
  • 1.  Run Python function located in separate .py file

    Posted Thu November 11, 2021 03:32 PM
    Hi,

    Is there a way to use the `SPSSINC PROGRAM` but load the Python code from an external .py file instead of specifying the Python code inside the .sps file?

    My current workflow for Python scripting in SPSS is the following
    - Write the python code in an external IDE (Visual studio code) because it's much more convenient
    - Write unit tests for my python script to make sure it works as expected
    - Copy paste the python code inside the BEGIN/END PROGRAM Python in a .sps file

    This is very time consuming and does not allow reusability of my Python scripts in several .sps files. So I wonder if there is a way to have all my Python scripts in .py source files and tell a SPSS script to load the functions from those files.

    A simple example would be this reg exp function described Using regular expressions in SPSS where I'd like the SearchZip to live in its own .py file

    I looked into Creating and editing extension bundles and while that would probably work, it seems like an overkill just for reusing some simple py functions

    thanks in advance
    Jan

    ------------------------------
    Jan
    ------------------------------


  • 2.  RE: Run Python function located in separate .py file
    Best Answer

    Posted Thu November 11, 2021 03:59 PM
    The SPSSINC PROGRAM extension command imports the specified module and runs the function.  After you install it from the Extension Hub, press F1 on an instance of the command (SPSSINC PROGRAM is enough) to see the details.

    You can, alternatively, just use a BEGIN/END program block containing the import and invocation code.

    For both of these approaches, the .py code does not need to be in the syntax window, but the location of the module must be on the Python search path.  You can run SHOW EXT from the syntax window or display sys.path in Python to see the locations where Python will look.  If you create a sitecustomize.py file in the lib/site-packages folder under your Statistics installation (or wherever you have set for Python via Edit > Options > Files) and append additional locations to sys.path, your modules can be in any of those locations.

    I haven't used VS Code lately (I use WingIDE), but if it has the ability to set the Python executable to use or otherwise manipulate the Python path, you can run SPSS directly from Python.  Read about External Mode if you want to try that.

    --





  • 3.  RE: Run Python function located in separate .py file

    Posted Thu November 11, 2021 05:52 PM
    Hi @Jon Peck

    thanks a lot for your answer. It works as expected and I can  indeed run my py function using​ for instance

    SPSSINC TRANS RESULT=Zip TYPE=5 /FORMULA mymodule.SearchZip(Address).

    cheers
    Jan

    ------------------------------
    Jan
    ------------------------------