* Check existence of a given variable in SPSS with Python script. * Command to be executed depends on the existence of a given variable. * Format is "varname ; command if varname exists; command if it does not exist" * Raynald Levesque www.spsstools.net 2005/10/11. GET FILE='c:\program files\spss\employee data.sav'. COMPUTE VarA = 3 . HOST COMMAND=['ECHO VarA; COMPUTE VarA=2*VarA .; COMPUTE VarA=1.> c:\temp\varExists.txt']. * The above HOST COMMAND creates a text file to pass parameters to the python script. * Parameters are delimited by ";" Each command must end with a ".". * The above varExists.txt file means that * if VarA exists, the command in the 2nd parameter "COMPUTE VarA=2*VarA." will be executed. * if VarA does NOT exist, the command in the 3rd parameter "COMPUTE VarA=1" will be executed. * Macro calls or INSERT FILE commands could also be used instead of the simple commands used above. *------------------------------. BEGIN PROGRAM python. import spss, win32api try: f = open(r'c:\temp\varExists.txt','r') s = f.readline() f.close() win32api.DeleteFile(r'c:\temp\varExists.txt') except: print "\n ***Error by Python script" if f and s: vec = s.split(";") varExists = 0 for i in range( spss.GetVariableCount() ): varName = spss.GetVariableName(i) if varName.upper() == vec[0].upper(): varExists = 1 print "\n*** variable exists" break if varExists == 0 and vec[2].strip() <> "": spss.Submit(vec[2]) print "\n*** variable did NOT exist" elif varExists == 1 and vec[1].strip <> "": spss.Submit(vec[1]) END PROGRAM. *------------------------------. EXECUTE. **************************************************************************************. * Short command version (that is a version that is easy to use on a DAILY BASIS). * the above python program is saved in "c:\temp\varExists.sps". * Include the following macro in the macro.sps file. *////////////////////////////. DEFINE !VarExists(!POS=!CMDEND) HOST COMMAND=[!QUOTE(!CONCAT('ECHO ',!UNQUOTE(!1), !UNQUOTE('> c:\temp\varExists.txt')))]. INSERT FILE="c:\temp\varExists.sps". !ENDDEFINE. *////////////////////////////. * Example 1: variable exists. GET FILE='c:\program files\spss\employee data.sav'. COMPUTE VarA=2. !VarExists "VarA; FREQ VAR=VarA .; COMPUTE VarA=1.". EXECUTE. * Example 2: when variable does not exist. GET FILE='c:\program files\spss\employee data.sav'. !VarExists "VarA; FREQ VAR=VarA .; COMPUTE VarA=1.". EXECUTE. * Example 3: multiline commands. * Use macros to define what needs to be done in each case. DEFINE !whenExist() COMPUTE VarA = VarA * 2. FREQ VAR = VarA !ENDDEFINE. DEFINE !whenNotExist() COMPUTE VarA = 3. TITLE "varA did not exist". !ENDDEFINE. GET FILE='c:\program files\spss\employee data.sav'. !VarExists "VarA; !whenExist .; !whenNotExist.". EXECUTE.