Search code examples
pythonspss

Python loop error in SPSS syntax only if i run the same code twice


I'm quite new in python programming.

I'm trying to automate some tabulations in SPSS using python (and i kind of managed it...) using a loop and some python code, but it works fine only the first time i run the syntax, the second time it tabulates only once:

I have an SPSS file with different projects merged together (i.e. different countries) , so first i try to extract a list of projects using a built in function. Once i have my list of project i run a loop and i change the spss syntax for the case selection and tabulation.

this is the code:

begin program.
import spss

#Function that extracts the data from spss
def DatiDaSPSS(vars, num):
  if num == 0:
    num = spss.GetCaseCount()
  if vars == None:
    varNums = range(spss.GetVariableCount())
  else:
    allvars = [spss.GetVariableName(i) for i in range(spss.GetVariableCount())]
    varNums = [allvars.index(i) for i in vars]
  data = spss.Cursor(varNums)
  pydata = data.fetchmany(num)
  data.close()
  return pydata

#store the result of the function into a list: 
all_prj=DatiDaSPSS(vars=["Project"],num=0)

#remove duplicates and keep only the country that i need:
prj_list=list(set([i[0] for i in all_prj]))


#loop for the tabulation:       
for i in range(len(prj_list)):
    prj_now=str(prj_list[i])

    spss.Submit("""

    compute filter_$=Project='%s'.
    filter by filter_$.
    exe.

    TEXT "Country"
    /OUTLINE HEADING="%s" TITLE="Country".

    CTABLES
      /VLABELS VARIABLES=HisInterviewer HisResult DISPLAY=DEFAULT
      /TABLE HisInterviewer [C][COUNT F40.0, ROWPCT.COUNT PCT40.1] BY HisResult [C]
      /CATEGORIES VARIABLES=HisInterviewer HisResult ORDER=A KEY=VALUE EMPTY=EXCLUDE TOTAL=YES 
        POSITION=AFTER
      /CRITERIA CILEVEL=95. 
    """ %(prj_now,prj_now))
end program.

When i run it the second time it shows only the last value of the list (and only one tabulation). If i restart SPSS it works fine the first time.

Is it because of the function?

i'm using spss25


Solution

  • can I reply myself, should i edit the discussion or maybe delete it? i think i found out the reason, i guess the function picks up only the values that are already selected, i tried now adding this SPSS code before the begin and it seems to be working:

    use all.
    exe.
    begin program.
    ...
    

    at the last loop there is a filter on the data and i removed it before of running the script. please let me know if you want me to edit or remove the message