Quickly import custom SPSS commands from Python

2019-05-11 03:37发布

I have written a neat Python module that contains some custom SPSS functions for my coworkers to use. However, to use the functionality, they first need to type BEGIN PROGRAM. Import module etc... before actually calling the function. Because most of them aren't tech savvy, I'm looking to make things easier.

Now they have to type something like this:

BEGIN PROGRAM.
import sys
sys.path.append("C:/Python scripts")
import mymodule
mymodule.custom_function('a','c')
END PROGRAM.

Is there a way I can write some SPSS-macro that will call the functions from my Python module in a single line? Like this:

!mymodule.custom_function varlist=a,b

I've tried defining a normal SPSS-macro and writing the BEGIN PROGRAM etc. in the macro body, but this yields an error. It seems that a macro-body can only contain valid SPSS syntax and no python code.

Is there another solution?

1条回答
smile是对你的礼貌
2楼-- · 2019-05-11 04:06

There are several possible solutions. If you want to have a standard set of Python functions loaded automatically, you can create a startup script. It would be named StartClient_.py and placed in the scripts directory under the Statistics installation. That will be executed each time Statistics is launched. (This can be generalized using the STATS OPEN PROJECT extension command that can do a lot of things when it is invoked, including writing a startup script.)

Another solution if you just want users to be able to run Python functions without facing any Python code or BEGIN/END program is to use the SPSSINC PROGRAM extension command (Utilities > Run Python Program). It take a module and function to run and whatever parameters you want to specify.

Here's an example: SPSSINC PROGRAM testpgm.mypgn x=age y = income z=.05.

As the developer, to make this work see the syntax help for this command. The command loads the module and passes the parameters to your code using sys.argv.

If you have mostly point and click users, you could just create a few custom dialog boxes that hold the Python code and have users install them.

查看更多
登录 后发表回答