Python script help - I though this was relatively simple

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

Python script help - I though this was relatively simple

Tim AT Home

I have a pretty simple I thought python script to format my tables output.

It runs without issues as far as I can tell BUT the page formatting is not

working.  I define with the function definition in points what I want for

top, left, right and bottom margins.  I select the output and set the print

options – no errors – but not working – I still have to go to page setup and

set the margins for it to print right.  Can anyone see anything wrong below??

 

 

 

 

#****                      START  MODULE                *****

#****                      START  MODULE                *****

#    1-MODIFIED DECEMBER 2007 TO REDUCE MANY FILES TO 1

#    2-MODIFIED MAY 2009 Version 17

#    3-MODIFIED JUNE 2009 FOR PYTHON

#    4-MODIFIED APRIL 28 2012 TO GET TO WORK AGAIN

#    5-MODIFIED NOV 10 2013 IGNORES MERGING DO NOT OUTPUT HTM OR PDF.

#    6-MODIFIED Mar 13 2015 MAYBE IT FINALLY WORKS.

 

"""This function will serve as my primary output formatting function

   .It removes all ouptut but pivot tables (CTables) and adds page breaks

   .It set the print options

   .It handles table numbering and table of contents creation

   .It saves output versions along the way and ultimately in various formats – eliminate eventually

"""

 

__author__ = "TWH"

__version__ = "1.0.5"

 

def OutputRoutine(myor = '2', \

                  mytm = '18', \

                  mylm = '9', \

                  myrm = '9', \

                  mybm = '18', \

                  mypn = '1', \

                  UseTableNumbering = True, \

                  UseTableOfContents = False, \

                  UseHTMLMarks = False, \

                  CleanUp = True, \

                  OutputSPV = True, \

                  OutputPDF = True, \

                  OutputHTM = False, \

                  OutputXLS = False, \

                  OutputPPT = False):

 

 

    import spss  #; help (spss)

   

 

    # CALL & START SPSS CLIENT

 

    import SpssClient

    SpssClient.StartClient()

   

    

    # KEEP - GET DESIGNATED OUTPUT DOC

    # If multiple output docs exist - get the list of output docs first and use a reference

    # MyOutputDocLists = SpssClient.GetOutputDocuments()

    # FirstOutputDoc = MyOutputDocLists.GetItemAt(0)

   

 

    # SELECTS ALL FOR DELETION EXCEPT RELEVANT PIVOT TABLES

 

    try:

        MyOutputDocLists = SpssClient.GetOutputDocuments()

        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()

 

        # Should change this to read directory of open syntax document

        MyCurrentPath = r'''c:\\Work_Home\\Other\\SPSS\\ExampleSPSS\\''' #; print MyCurrentPath

 

        # Should change this to read name from open syntax document

        flename = r'''flename''' #; print flename

   

        # SAVE BEFORE ANYTHING

        MyOutputDoc.SaveAs(MyCurrentPath + flename + "_ORG_" + ".spv")

 

        MyOutputDoc.ClearSelection()

        MyOutputDoc.SelectAllCharts()

        MyOutputDoc.Delete()

        MyOutputDoc.SelectAllLogs()

        MyOutputDoc.Delete()

        MyOutputDoc.SelectAllNotes()

        MyOutputDoc.Delete()

        MyOutputDoc.SelectAllText()

        MyOutputDoc.Delete()

        MyOutputDoc.SelectAllTitles()

        MyOutputDoc.Delete()

        MyOutputDoc.SelectAllWarnings()

        MyOutputDoc.Delete()

    except:

        raise

   

 

    ## PRINT(PAGE) SETUP

   

    try:

        MyOutputDocLists = SpssClient.GetOutputDocuments()

        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()

 

        #myor = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.Orientation)

        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.Orientation,myor)

 

        #mytm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.TopMargin)

        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.TopMargin,mytm)

 

        #mylm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.LeftMargin)

        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.LeftMargin,mylm)

 

        #myrm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.RightMargin)

        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.RightMargin,myrm)

 

        #mybm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.BottomMargin)

        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.BottomMargin,mybm)

 

        #mypn = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.StartingPageNumber)

        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.StartingPageNumber,mypn)

 

        #MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.SpaceBetweenItems,)

        #MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.PrintedChartSize,)

 

        # SAVE POST FORMATTING

        MyOutputDoc.SaveAs(MyCurrentPath + flename + "_M2_" + ".spv")

 

    except:

        raise

   

    

    #'TABLE NUMBERING, PAGE BREAK AND TABLE OF CONTENTS SETUP

    #'PROBE FOR TABLE NUMBERING AND TABLE OF CONTENTS.

    #'OPEN BOOKMARKS/TOC/HTML MARKUP FILES - RUN ON CLEANED OUPUT

 

    try:

        PTable = 0

 

        FileBookM1 = open(MyCurrentPath + r'''Bookmarks1.txt''', 'w')

        FileTOC2 = open(MyCurrentPath + r'''TOC.txt''', 'w')

        FileHTMLMarks = open(MyCurrentPath + r'''HTMLMarks.txt''', 'w')

 

        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()

        MyOutputItems = MyOutputDoc.GetOutputItems()

        for index in range(MyOutputItems.Size()):

            MyOutputItem = MyOutputItems.GetItemAt(index)

            if MyOutputItem.GetType() == SpssClient.OutputItemType.PIVOT:

                PTable += 1

                MyPivotTable = MyOutputItem.GetSpecificType()

                MyPivotTable.SetUpdateScreen(True)

                MyPivotTable.ClearSelection()

                CurrentTitle = MyPivotTable.GetTitleText()

 

                if PTable > 1:

                        MyOutputItem.SetPageBreak(True)

 

                if UseTableNumbering:

                    NewTitle = "Table: " + str(PTable) + " " + CurrentTitle

                    # print NewTitle

                    MyPivotTable.SelectTitle()

                    MyPivotTable.SetTitleText(NewTitle)

                    MyPivotTable.ClearSelection()

                    FileBookM1.write(">" + NewTitle + "\n")

                    if PTable == 1:

                        print "YES-TableNumbers"

                else:

                    if PTable == 1:

                        print "No-TableNumbers"

 

                if UseTableOfContents:

                    if UseTableNumbering:

                        NewTitleTOC = NewTitle

                    else:

                        NewTitleTOC = CurrentTitle

                    # print NewTitleTOC

                    FileTOC2.write(NewTitleTOC + "\n")

                    if PTable == 1:

                        print "YES-TOC"

                else:

                    if PTable == 1:

                        print "No-TOC"

 

                if UseHTMLMarks:

                    if UseTableNumbering:

                        NewTitle = r"""<a name=""" + NewTitle + r"""></a>"""

                        NewTitleHTMLRef = r"""<a href=#""" + NewTitle + r""">""" + "</a>"

                    else:

                        NewTitle = r"""<a name=""" + CurrentTitle + r"""></a>"""

                        NewTitleHTMLRef = r"""<a href=#""" + CurrentTitle + r""">""" + "</a>"

                    FileHTMLMarks.write(NewTitle + "\n")

                    FileHTMLMarks.write(NewTitleHTMLRef + "\n")

                    if PTable == 1:

                        print "YES-HTML"

                else:

                    if PTable == 1:

                        print "No-HTML"

 

 

        FileBookM1.close()

        FileTOC2.close()

        FileHTMLMarks.close()

 

        # SAVE POST NUMBERING, ETC

        if UseTableNumbering or UseTableOfContents or UseHTMLMarks:

            MyOutputDoc.SaveAs(MyCurrentPath + flename + "_M3_" + ".spv")

 

    except:

        raise

 

 

    try:

        if CleanUp:

          MySyntaxDocsList = SpssClient.GetSyntaxDocuments()

          for index in range(MySyntaxDocsList.Size(), 0, -1):

                 MySyntaxDocs = MySyntaxDocsList.GetItemAt(index-1)

                 MySyntaxDocs.CloseDocument()

    except:

        raise

   

 

   

    # SAVE DESIGNATED OUTPUT DOCUMENT

    try:

        MyOutputDoc.SetPromptToSave(True)

        if OutputSPV:

            MyOutputDoc.SaveAs(MyCurrentPath + flename + "_FNL_" + ".spv")

    except:

        raise

   

    

    # EXPORT AS PDF

    try:

        if OutputPDF:

            fileName = MyCurrentPath + flename + ".pdf"

            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatPdf)

    except:

        raise

 

 

    # EXPORT AS EXCEL

    try:

        if OutputXLS:

            fileName = MyCurrentPath + flename + ".xls"

            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatXls)

    except:

        raise

 

 

    # EXPORT AS POWERPOINT

    try:

        if OutputPPT:

            fileName = MyCurrentPath + flename + ".ppt"

            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatPpt)

   except:

        raise

 

 

    # EXPORT AS HTML

    try:

        if OutputHTM:

            fileName = MyCurrentPath + flename + ".html"

            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatHtml)

    except:

        raise

 

 

    # END SPSS CLIENT

 

    SpssClient.StopClient()

 

 

#****                      END    MODULE                *****

#****                      END    MODULE                *****

 

 

 

 

 

Thanks!

 

*********************************

Notice: This e-mail and any attachments may contain confidential and privileged information.  If you are not the intended recipient, please notify the sender immediately by return e-mail, do not use the information, delete this e-mail and destroy any copies.  Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal.  Email transmissions cannot be guaranteed to be secure or error free. The sender therefore does not accept any liability for errors or omissions in the contents of this message that arise as a result of email transmissions.

 

===================== To manage your subscription to SPSSX-L, send a message to [hidden email] (not to SPSSX-L), with no body text except the command. To leave the list, send the command SIGNOFF SPSSX-L For a list of commands to manage subscriptions, send the command INFO REFCARD
Reply | Threaded
Open this post in threaded view
|

Re: Python script help - I though this was relatively simple

David Marso
Administrator
I have no idea, but have you tried NOT "quoting" the arguments?
I suspect the API is expecting numbers but you are feeding it strings?
Just a guess, I don't have time to look up the definitions
Please reply to the list and not to my personal email.
Those desiring my consulting or training services please feel free to email me.
---
"Nolite dare sanctum canibus neque mittatis margaritas vestras ante porcos ne forte conculcent eas pedibus suis."
Cum es damnatorum possederunt porcos iens ut salire off sanguinum cliff in abyssum?"
Reply | Threaded
Open this post in threaded view
|

Re: Python script help - I though this was relatively simple

Tim AT Home
No - that’s no it - remove the quotes and I get an error - saying it must be
string not int





Thanks!

*********************************
Notice: This e-mail and any attachments may contain confidential and
privileged information.  If you are not the intended recipient, please
notify the sender immediately by return e-mail, do not use the information,
delete this e-mail and destroy any copies.  Any dissemination or use of this
information by a person other than the intended recipient is unauthorized
and may be illegal.  Email transmissions cannot be guaranteed to be secure
or error free. The sender therefore does not accept any liability for errors
or omissions in the contents of this message that arise as a result of email
transmissions.

-----Original Message-----
From: SPSSX(r) Discussion [mailto:[hidden email]] On Behalf Of
David Marso
Sent: Friday, March 13, 2015 2:24 PM
To: [hidden email]
Subject: Re: Python script help - I though this was relatively simple

I have no idea, but have you tried NOT "quoting" the arguments?
I suspect the API is expecting numbers but you are feeding it strings?
Just a guess, I don't have time to look up the definitions




-----
Please reply to the list and not to my personal email.
Those desiring my consulting or training services please feel free to email
me.
---
"Nolite dare sanctum canibus neque mittatis margaritas vestras ante porcos
ne forte conculcent eas pedibus suis."
Cum es damnatorum possederunt porcos iens ut salire off sanguinum cliff in
abyssum?"
--
View this message in context:
http://spssx-discussion.1045642.n5.nabble.com/Python-script-help-I-though-th
is-was-relatively-simple-tp5728997p5728998.html
Sent from the SPSSX Discussion mailing list archive at Nabble.com.

=====================
To manage your subscription to SPSSX-L, send a message to
[hidden email] (not to SPSSX-L), with no body text except the
command. To leave the list, send the command SIGNOFF SPSSX-L For a list of
commands to manage subscriptions, send the command INFO REFCARD

=====================
To manage your subscription to SPSSX-L, send a message to
[hidden email] (not to SPSSX-L), with no body text except the
command. To leave the list, send the command
SIGNOFF SPSSX-L
For a list of commands to manage subscriptions, send the command
INFO REFCARD
Reply | Threaded
Open this post in threaded view
|

Re: Python script help - I though this was relatively simple

Jon K Peck
In reply to this post by Tim AT Home
This script is way too long to debug through.  I suggest trying the STATS OUTPUT ATTRS extension command just for comparison.  It can be installed from the Utilities menu if it isn't already installed.  (File > Set Viewer Output Options).

The parameters at the scripting levels do need to be strings.


Jon Peck (no "h") aka Kim
Senior Software Engineer, IBM
[hidden email]
phone: 720-342-5621




From:        Tim Hennigar <[hidden email]>
To:        [hidden email]
Date:        03/13/2015 11:19 AM
Subject:        [SPSSX-L] Python script help - I though this was relatively simple
Sent by:        "SPSSX(r) Discussion" <[hidden email]>




I have a pretty simple I thought python script to format my tables output.
It runs without issues as far as I can tell BUT the page formatting is not
working.  I define with the function definition in points what I want for
top, left, right and bottom margins.  I select the output and set the print
options – no errors – but not working – I still have to go to page setup and
set the margins for it to print right.  Can anyone see anything wrong below??
 
 
 
 
#****                      START  MODULE                *****
#****                      START  MODULE                *****
#    1-MODIFIED DECEMBER 2007 TO REDUCE MANY FILES TO 1
#    2-MODIFIED MAY 2009 Version 17
#    3-MODIFIED JUNE 2009 FOR PYTHON
#    4-MODIFIED APRIL 28 2012 TO GET TO WORK AGAIN
#    5-MODIFIED NOV 10 2013 IGNORES MERGING DO NOT OUTPUT HTM OR PDF.
#    6-MODIFIED Mar 13 2015 MAYBE IT FINALLY WORKS.
 
"""This function will serve as my primary output formatting function
   .It removes all ouptut but pivot tables (CTables) and adds page breaks
   .It set the print options
   .It handles table numbering and table of contents creation
   .It saves output versions along the way and ultimately in various formats – eliminate eventually
"""
 
__author__ = "TWH"
__version__ = "1.0.5"
 
def OutputRoutine(myor = '2', \
                  mytm = '18', \
                  mylm = '9', \
                  myrm = '9', \
                  mybm = '18', \
                  mypn = '1', \
                  UseTableNumbering = True, \
                  UseTableOfContents = False, \
                  UseHTMLMarks = False, \
                  CleanUp = True, \
                  OutputSPV = True, \
                  OutputPDF = True, \
                  OutputHTM = False, \
                  OutputXLS = False, \
                  OutputPPT = False):
 
 
    import spss  #; help (spss)
   
 
    # CALL & START SPSS CLIENT
 
    import SpssClient
    SpssClient.StartClient()
   
   
    # KEEP - GET DESIGNATED OUTPUT DOC
    # If multiple output docs exist - get the list of output docs first and use a reference
    # MyOutputDocLists = SpssClient.GetOutputDocuments()
    # FirstOutputDoc = MyOutputDocLists.GetItemAt(0)
   
 
    # SELECTS ALL FOR DELETION EXCEPT RELEVANT PIVOT TABLES
 
    try:
        MyOutputDocLists = SpssClient.GetOutputDocuments()
        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()
 
        # Should change this to read directory of open syntax document
        MyCurrentPath = r'''c:\\Work_Home\\Other\\SPSS\\ExampleSPSS\\''' #; print MyCurrentPath
 
        # Should change this to read name from open syntax document
        flename = r'''flename''' #; print flename
   
        # SAVE BEFORE ANYTHING
        MyOutputDoc.SaveAs(MyCurrentPath + flename + "_ORG_" + ".spv")
 
        MyOutputDoc.ClearSelection()
        MyOutputDoc.SelectAllCharts()
        MyOutputDoc.Delete()
        MyOutputDoc.SelectAllLogs()
        MyOutputDoc.Delete()
        MyOutputDoc.SelectAllNotes()
        MyOutputDoc.Delete()
        MyOutputDoc.SelectAllText()
        MyOutputDoc.Delete()
        MyOutputDoc.SelectAllTitles()
        MyOutputDoc.Delete()
        MyOutputDoc.SelectAllWarnings()
        MyOutputDoc.Delete()
    except:
        raise
   
 
    ## PRINT(PAGE) SETUP
   
    try:
        MyOutputDocLists = SpssClient.GetOutputDocuments()
        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()
 
        #myor = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.Orientation)
        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.Orientation,myor)
 
        #mytm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.TopMargin)
        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.TopMargin,mytm)
 
        #mylm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.LeftMargin)
        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.LeftMargin,mylm)
 
        #myrm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.RightMargin)
        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.RightMargin,myrm)
 
        #mybm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.BottomMargin)
        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.BottomMargin,mybm)
 
        #mypn = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.StartingPageNumber)
        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.StartingPageNumber,mypn)
 
        #MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.SpaceBetweenItems,)
        #MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.PrintedChartSize,)
 
        # SAVE POST FORMATTING
        MyOutputDoc.SaveAs(MyCurrentPath + flename + "_M2_" + ".spv")
 
    except:
        raise
   
   
    #'TABLE NUMBERING, PAGE BREAK AND TABLE OF CONTENTS SETUP
    #'PROBE FOR TABLE NUMBERING AND TABLE OF CONTENTS.
    #'OPEN BOOKMARKS/TOC/HTML MARKUP FILES - RUN ON CLEANED OUPUT
 
    try:
        PTable = 0
 
        FileBookM1 = open(MyCurrentPath + r'''Bookmarks1.txt''', 'w')
        FileTOC2 = open(MyCurrentPath + r'''TOC.txt''', 'w')
        FileHTMLMarks = open(MyCurrentPath + r'''HTMLMarks.txt''', 'w')
 
        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()
        MyOutputItems = MyOutputDoc.GetOutputItems()
        for index in range(MyOutputItems.Size()):
            MyOutputItem = MyOutputItems.GetItemAt(index)
            if MyOutputItem.GetType() == SpssClient.OutputItemType.PIVOT:
                PTable += 1
                MyPivotTable = MyOutputItem.GetSpecificType()
                MyPivotTable.SetUpdateScreen(True)
                MyPivotTable.ClearSelection()
                CurrentTitle = MyPivotTable.GetTitleText()
 
                if PTable > 1:
                        MyOutputItem.SetPageBreak(True)
 
                if UseTableNumbering:
                    NewTitle = "Table: " + str(PTable) + " " + CurrentTitle
                    # print NewTitle
                    MyPivotTable.SelectTitle()
                    MyPivotTable.SetTitleText(NewTitle)
                    MyPivotTable.ClearSelection()
                    FileBookM1.write(">" + NewTitle + "\n")
                    if PTable == 1:
                        print "YES-TableNumbers"
                else:
                    if PTable == 1:
                        print "No-TableNumbers"
 
                if UseTableOfContents:
                    if UseTableNumbering:
                        NewTitleTOC = NewTitle
                    else:
                        NewTitleTOC = CurrentTitle
                    # print NewTitleTOC
                    FileTOC2.write(NewTitleTOC + "\n")
                    if PTable == 1:
                        print "YES-TOC"
                else:
                    if PTable == 1:
                        print "No-TOC"
 
                if UseHTMLMarks:
                    if UseTableNumbering:
                        NewTitle = r"""<a name=""" + NewTitle + r"""></a>"""
                        NewTitleHTMLRef = r"""<a href=#""" + NewTitle + r""">""" + "</a>"
                    else:
                        NewTitle = r"""<a name=""" + CurrentTitle + r"""></a>"""
                        NewTitleHTMLRef = r"""<a href=#""" + CurrentTitle + r""">""" + "</a>"
                    FileHTMLMarks.write(NewTitle + "\n")
                    FileHTMLMarks.write(NewTitleHTMLRef + "\n")
                    if PTable == 1:
                        print "YES-HTML"
                else:
                    if PTable == 1:
                        print "No-HTML"
 
 
        FileBookM1.close()
        FileTOC2.close()
        FileHTMLMarks.close()
 
        # SAVE POST NUMBERING, ETC
        if UseTableNumbering or UseTableOfContents or UseHTMLMarks:
            MyOutputDoc.SaveAs(MyCurrentPath + flename + "_M3_" + ".spv")
 
    except:
        raise
 
 
    try:
        if CleanUp:
          MySyntaxDocsList = SpssClient.GetSyntaxDocuments()
          for index in range(MySyntaxDocsList.Size(), 0, -1):
                 MySyntaxDocs = MySyntaxDocsList.GetItemAt(index-1)
                 MySyntaxDocs.CloseDocument()
    except:
        raise
   
 
   
    # SAVE DESIGNATED OUTPUT DOCUMENT
    try:
        MyOutputDoc.SetPromptToSave(True)
        if OutputSPV:
            MyOutputDoc.SaveAs(MyCurrentPath + flename + "_FNL_" + ".spv")
    except:
        raise
   
   
    # EXPORT AS PDF
    try:
        if OutputPDF:
            fileName = MyCurrentPath + flename + ".pdf"
            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatPdf)
    except:
        raise
 
 
    # EXPORT AS EXCEL
    try:
        if OutputXLS:
            fileName = MyCurrentPath + flename + ".xls"
            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatXls)
    except:
        raise
 
 
    # EXPORT AS POWERPOINT
    try:
        if OutputPPT:
            fileName = MyCurrentPath + flename + ".ppt"
            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatPpt)
   except:
        raise
 
 
    # EXPORT AS HTML
    try:
        if OutputHTM:
            fileName = MyCurrentPath + flename + ".html"
            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatHtml)
    except:
        raise
 
 
    # END SPSS CLIENT
 
    SpssClient.StopClient()
 
 
#****                      END    MODULE                *****
#****                      END    MODULE                *****
 
 
 
 
 
Thanks!
 
*********************************
Notice: This e-mail and any attachments may contain confidential and privileged information.  If you are not the intended recipient, please notify the sender immediately by return e-mail, do not use the information, delete this e-mail and destroy any copies.  Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal.  Email transmissions cannot be guaranteed to be secure or error free. The sender therefore does not accept any liability for errors or omissions in the contents of this message that arise as a result of email transmissions.
 

===================== To manage your subscription to SPSSX-L, send a message to LISTSERV@... (not to SPSSX-L), with no body text except the command. To leave the list, send the command SIGNOFF SPSSX-L For a list of commands to manage subscriptions, send the command INFO REFCARD

===================== To manage your subscription to SPSSX-L, send a message to [hidden email] (not to SPSSX-L), with no body text except the command. To leave the list, send the command SIGNOFF SPSSX-L For a list of commands to manage subscriptions, send the command INFO REFCARD

Reply | Threaded
Open this post in threaded view
|

Re: Python script help - I though this was relatively simple

Albert-Jan Roskam-2
In reply to this post by Tim AT Home
Hi,

Before doing anything else, I would *really* split the code up into some meaningful, simple functions.
Here is an untested example: http://pastebin.com/ju0mpSjn . Now you can easily outcomment bits of the code in the function main() and debug every separate unit.


A few remarks:


You often used:

try:
   # lots of code
except:  # bare except
   raise

Using bare excepts is frowned upon as it masks errors, moreover, what's the point of catching an/any error, only to immediately raise it again?


It is a common convention (which is violated in the SpssClient documentation!) to only let class names start with caps, not variable names and so on (google for Python PEP8).


 Regards,

Albert-Jan




~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a

fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




>________________________________
> From: Tim Hennigar <[hidden email]>
>To: [hidden email]
>Sent: Friday, March 13, 2015 6:18 PM
>Subject: [SPSSX-L] Python script help - I though this was relatively simple
>
>
>
>I have a pretty simple I thought python script to format my tables output.
>It runs without issues as far as I can tell BUT the page formatting is not
>working.  I define with the function definition in points what I want for
>top, left, right and bottom margins.  I select the output and set the print
>options – no errors – but not working – I still have to go to page setup and
>set the margins for it to print right.  Can anyone see anything wrong below??
>
>
>
>
>#****                      START  MODULE                *****
>#****                      START  MODULE                *****
>#    1-MODIFIED DECEMBER 2007 TO REDUCE MANY FILES TO 1
>#    2-MODIFIED MAY 2009 Version 17
>#    3-MODIFIED JUNE 2009 FOR PYTHON
>#    4-MODIFIED APRIL 28 2012 TO GET TO WORK AGAIN
>#    5-MODIFIED NOV 10 2013 IGNORES MERGING DO NOT OUTPUT HTM OR PDF.
>#    6-MODIFIED Mar 13 2015 MAYBE IT FINALLY WORKS.
>
>"""This function will serve as my primary output formatting function
>   .It removes all ouptut but pivot tables (CTables) and adds page breaks
>   .It set the print options
>   .It handles table numbering and table of contents creation
>   .It saves output versions along the way and ultimately in various formats – eliminate eventually
>"""
>
>__author__ = "TWH"
>__version__ = "1.0.5"
>
>def OutputRoutine(myor = '2', \
>                  mytm = '18', \
>                  mylm = '9', \
>                  myrm = '9', \
>                  mybm = '18', \
>                  mypn = '1', \
>                  UseTableNumbering = True, \
>                  UseTableOfContents = False, \
>                  UseHTMLMarks = False, \
>                  CleanUp = True, \
>                  OutputSPV = True, \
>                  OutputPDF = True, \
>                  OutputHTM = False, \
>                  OutputXLS = False, \
>                  OutputPPT = False):
>
>
>    import spss  #; help (spss)
>    
>
>    # CALL & START SPSS CLIENT
>
>    import SpssClient
>    SpssClient.StartClient()
>    
>    
>    # KEEP - GET DESIGNATED OUTPUT DOC
>    # If multiple output docs exist - get the list of output docs first and use a reference
>    # MyOutputDocLists = SpssClient.GetOutputDocuments()
>    # FirstOutputDoc = MyOutputDocLists.GetItemAt(0)
>    
>
>    # SELECTS ALL FOR DELETION EXCEPT RELEVANT PIVOT TABLES
>
>    try:
>        MyOutputDocLists = SpssClient.GetOutputDocuments()
>        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()
>
>        # Should change this to read directory of open syntax document
>        MyCurrentPath = r'''c:\\Work_Home\\Other\\SPSS\\ExampleSPSS\\''' #; print MyCurrentPath
>
>        # Should change this to read name from open syntax document
>        flename = r'''flename''' #; print flename
>    
>        # SAVE BEFORE ANYTHING
>        MyOutputDoc.SaveAs(MyCurrentPath + flename + "_ORG_" + ".spv")
>
>        MyOutputDoc.ClearSelection()
>        MyOutputDoc.SelectAllCharts()
>        MyOutputDoc.Delete()
>        MyOutputDoc.SelectAllLogs()
>        MyOutputDoc.Delete()
>        MyOutputDoc.SelectAllNotes()
>        MyOutputDoc.Delete()
>        MyOutputDoc.SelectAllText()
>        MyOutputDoc.Delete()
>        MyOutputDoc.SelectAllTitles()
>        MyOutputDoc.Delete()
>        MyOutputDoc.SelectAllWarnings()
>        MyOutputDoc.Delete()
>    except:
>        raise
>    
>
>    ## PRINT(PAGE) SETUP
>    
>    try:
>        MyOutputDocLists = SpssClient.GetOutputDocuments()
>        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()
>
>        #myor = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.Orientation)
>        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.Orientation,myor)
>
>        #mytm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.TopMargin)
>        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.TopMargin,mytm)
>
>        #mylm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.LeftMargin)
>        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.LeftMargin,mylm)
>
>        #myrm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.RightMargin)
>        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.RightMargin,myrm)
>
>        #mybm = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.BottomMargin)
>        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.BottomMargin,mybm)
>
>        #mypn = MyOutputDoc.GetPrintOptions(SpssClient.PrintOptions.StartingPageNumber)
>        MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.StartingPageNumber,mypn)
>
>        #MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.SpaceBetweenItems,)
>        #MyOutputDoc.SetPrintOptions(SpssClient.PrintOptions.PrintedChartSize,)
>
>        # SAVE POST FORMATTING
>        MyOutputDoc.SaveAs(MyCurrentPath + flename + "_M2_" + ".spv")
>
>    except:
>        raise
>    
>    
>    #'TABLE NUMBERING, PAGE BREAK AND TABLE OF CONTENTS SETUP
>    #'PROBE FOR TABLE NUMBERING AND TABLE OF CONTENTS.
>    #'OPEN BOOKMARKS/TOC/HTML MARKUP FILES - RUN ON CLEANED OUPUT
>
>    try:
>        PTable = 0
>
>        FileBookM1 = open(MyCurrentPath + r'''Bookmarks1.txt''', 'w')
>        FileTOC2 = open(MyCurrentPath + r'''TOC.txt''', 'w')
>        FileHTMLMarks = open(MyCurrentPath + r'''HTMLMarks.txt''', 'w')
>
>        MyOutputDoc = SpssClient.GetDesignatedOutputDoc()
>        MyOutputItems = MyOutputDoc.GetOutputItems()
>        for index in range(MyOutputItems.Size()):
>            MyOutputItem = MyOutputItems.GetItemAt(index)
>            if MyOutputItem.GetType() == SpssClient.OutputItemType.PIVOT:
>                PTable += 1
>                MyPivotTable = MyOutputItem.GetSpecificType()
>                MyPivotTable.SetUpdateScreen(True)
>                MyPivotTable.ClearSelection()
>                CurrentTitle = MyPivotTable.GetTitleText()
>
>                if PTable > 1:
>                        MyOutputItem.SetPageBreak(True)
>
>                if UseTableNumbering:
>                    NewTitle = "Table: " + str(PTable) + " " + CurrentTitle
>                    # print NewTitle
>                    MyPivotTable.SelectTitle()
>                    MyPivotTable.SetTitleText(NewTitle)
>                    MyPivotTable.ClearSelection()
>                    FileBookM1.write(">" + NewTitle + "\n")
>                    if PTable == 1:
>                        print "YES-TableNumbers"
>                else:
>                    if PTable == 1:
>                        print "No-TableNumbers"
>
>                if UseTableOfContents:
>                    if UseTableNumbering:
>                        NewTitleTOC = NewTitle
>                    else:
>                        NewTitleTOC = CurrentTitle
>                    # print NewTitleTOC
>                    FileTOC2.write(NewTitleTOC + "\n")
>                    if PTable == 1:
>                        print "YES-TOC"
>                else:
>                    if PTable == 1:
>                        print "No-TOC"
>
>                if UseHTMLMarks:
>                    if UseTableNumbering:
>                        NewTitle = r"""<a name=""" + NewTitle + r"""></a>"""
>                        NewTitleHTMLRef = r"""<a href=#""" + NewTitle + r""">""" + "</a>"
>                    else:
>                        NewTitle = r"""<a name=""" + CurrentTitle + r"""></a>"""
>                        NewTitleHTMLRef = r"""<a href=#""" + CurrentTitle + r""">""" + "</a>"
>                    FileHTMLMarks.write(NewTitle + "\n")
>                    FileHTMLMarks.write(NewTitleHTMLRef + "\n")
>                    if PTable == 1:
>                        print "YES-HTML"
>                else:
>                    if PTable == 1:
>                        print "No-HTML"
>
>
>        FileBookM1.close()
>        FileTOC2.close()
>        FileHTMLMarks.close()
>
>        # SAVE POST NUMBERING, ETC
>        if UseTableNumbering or UseTableOfContents or UseHTMLMarks:
>            MyOutputDoc.SaveAs(MyCurrentPath + flename + "_M3_" + ".spv")
>
>    except:
>        raise
>
>
>    try:
>        if CleanUp:
>          MySyntaxDocsList = SpssClient.GetSyntaxDocuments()
>          for index in range(MySyntaxDocsList.Size(), 0, -1):
>                 MySyntaxDocs = MySyntaxDocsList.GetItemAt(index-1)
>                 MySyntaxDocs.CloseDocument()
>    except:
>        raise
>    
>
>    
>    # SAVE DESIGNATED OUTPUT DOCUMENT
>    try:
>        MyOutputDoc.SetPromptToSave(True)
>        if OutputSPV:
>            MyOutputDoc.SaveAs(MyCurrentPath + flename + "_FNL_" + ".spv")
>    except:
>        raise
>    
>    
>    # EXPORT AS PDF
>    try:
>        if OutputPDF:
>            fileName = MyCurrentPath + flename + ".pdf"
>            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatPdf)
>    except:
>        raise
>
>
>    # EXPORT AS EXCEL
>    try:
>        if OutputXLS:
>            fileName = MyCurrentPath + flename + ".xls"
>            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatXls)
>    except:
>        raise
>
>
>    # EXPORT AS POWERPOINT
>    try:
>        if OutputPPT:
>            fileName = MyCurrentPath + flename + ".ppt"
>            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatPpt)
>   except:
>        raise
>
>
>    # EXPORT AS HTML
>    try:
>        if OutputHTM:
>            fileName = MyCurrentPath + flename + ".html"
>            MyOutputDoc.ExportDocument(SpssClient.SpssExportSubset.SpssVisible,fileName,SpssClient.DocExportFormat.SpssFormatHtml)
>    except:
>        raise
>
>
>    # END SPSS CLIENT
>
>    SpssClient.StopClient()
>
>
>#****                      END    MODULE                *****
>#****                      END    MODULE                *****
>
>
>
>
>
>Thanks!
>
>*********************************
>Notice:This e-mail and any attachments may contain confidential and privileged information.  If you are not the intended recipient, please notify the sender immediately by return e-mail, do not use the information, delete this e-mail and destroy any copies.  Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal.  Email transmissions cannot be guaranteed to be secure or error free. The sender therefore does not accept any liability for errors or omissions in the contents of this message that arise as a result of email transmissions.
>
=====================
To manage your subscription to SPSSX-L, send a message to [hidden email] (not to SPSSX-L), with no body text except the
command. To leave the list, send the command
SIGNOFF SPSSX-L
For a list of commands to manage subscriptions, send the command
INFO REFCARD
>
>

=====================
To manage your subscription to SPSSX-L, send a message to
[hidden email] (not to SPSSX-L), with no body text except the
command. To leave the list, send the command
SIGNOFF SPSSX-L
For a list of commands to manage subscriptions, send the command
INFO REFCARD