'How to create a class in Python to work with an external API (SAP2000)

I´m quite new in programming and even more when it comes to Object Oriented programming. I’m trying to connect through Python to an external software (SAP2000, an structural engineering software). This program comes with an API to connect and there is an example in the help (http://docs.csiamerica.com/help-files/common-api(from-sap-and-csibridge)/Example_Code/Example_7_(Python).htm).

This works pretty well but I would like to divide the code so that I can create one function for opening the program, several functions to work with it and another one to close. This would provide me flexibility to make different calculations as desired and close it afterwards.

Here is the code I have so far where enableloadcases() is a function that operates once the instance is created.

import os
import sys
import comtypes.client
import pandas as pd

def openSAP2000(path,filename):
    ProgramPath = "C:\Program Files (x86)\Computers and Structures\SAP2000 20\SAP2000.exe"
    APIPath = path
    ModelPath = APIPath + os.sep + filename
    mySapObject = comtypes.client.GetActiveObject("CSI.SAP2000.API.SapObject")

    #start SAP2000 application
    mySapObject.ApplicationStart()

    #create SapModel object
    SapModel = mySapObject.SapModel

    #initialize model
    SapModel.InitializeNewModel()

    ret = SapModel.File.OpenFile(ModelPath)

    #run model (this will create the analysis model)
    ret = SapModel.Analyze.RunAnalysis()

def closeSAP2000():
    #ret = mySapObject.ApplicationExit(False)
    SapModel = None
    mySapObject = None


def enableloadcases(case_id):
    '''
        The function activates LoadCases for output
    '''
    ret = SapModel.Results.Setup.SetCaseSelectedForOutput(case_id)

From another module, I call the function openSAP2000() and it works fine but when I call the function enableloadcases() an error says AttributeError: type object ‘SapModel’ has no attribute ‘Results’.

I believe this must be done by creating a class and after calling the functions inside but I honestly don´t know how to do it.

Could you please help me?

Thank you very much.



Solution 1:[1]

Thank you very much for the help. I managed to solve the problem. It was as simple and stupid as marking SapModel variable as global.

Now it works fine.

Thank you anyway.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juancar