Ask Your Question
5

Raise psspy ierr as python exception

asked 2013-09-03 10:13:23 -0500

jsexauer gravatar image

As I'm sure you've realized after playing with the API for a while, its pretty easy to never check your ierrs when working with the API. I wrote this decorator which will apply itself to all the psspy functions which generate an ierr and check at each call that ierr is not 0.

If it the function does generate an ierr, it raises a Python exception with detailed debug information related to the ierr gleamed from the docstring.

For example, calling

psspy.case(r"nonexistantFile")

now raises:

Exception: psspy.case generated ierr = 3: error opening SFILE.

Here is the code:

def raisePsspyError(psspyFunc):
    """This decorator raises a python exception whenever a psspy
       function returns an ierr that is not 0. """
    def callPsspyFunc(*args, **kwargs):
        ans = psspyFunc(*args, **kwargs)
        if type(ans) is tuple:
            ierr = ans[0]   # ierr is always first element of tuple
        elif type(ans) is int:
            ierr = ans      # function only returns ierr
        else:
            raise Exception("Unkonwn return type %s." % type(ans))
        if ierr != 0:
            # Find all the errors documented in the doc string
            errDoc = psspyFunc.__doc__[psspyFunc.__doc__.find('IERR = 0'):]
            errs = {}
            for errStr in errDoc.split('\n'):
                try:
                    errNum = errStr.split('=')[1].strip()[0]
                    errDesc = errStr.split('=')[1].strip()[2:]
                    errs[int(errNum)] = errDesc
                except:
                    pass
            msg = "psspy." + psspyFunc.__name__ + " generated ierr = " + \
                str(ierr) + ": " + errs[ierr]
            raise Exception(msg)
        else:
            return ans
    return callPsspyFunc

# Apply our decorator to all psspy function which return an ierr
import types
for k,v in vars(psspy).items():
    if isinstance(v, types.FunctionType):
        if v.__doc__.find('IERR = 0') > 0:
            vars(psspy)[k] = raisePsspyError(v)

if __name__ == '__main__':
    import psspy
    psspy.case(r"nonexistantFile.sav")  # Will raise a python exception instead
                                        #  of just going mairly on its way

(maintained at this gist: https://gist.github.com/jsexauer/6425120 )

edit retag flag offensive close merge delete

Comments

This is fantastic. I've always thought about doing something like this, but never had the drive. Thanks a bunch for this

nyga0082 gravatar imagenyga0082 ( 2013-09-03 14:32:32 -0500 )edit

@jsexauer fantastic work, neat trick to pull the ierr info out of the help string!

JervisW gravatar imageJervisW ( 2013-09-11 00:34:19 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
0

answered 2013-09-12 16:07:22 -0500

EBahr gravatar image

Not sure if you knew this or not, but there is actually a built in psspy attribute, throwPsseExeption, that does something similar.

For example:

psspy.throwPsseException = True
psspy.case(r"nonexistantFile")

will output:

File not found. nonexistantFile.sav (OpnApplFil/OPNPTI)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File ".\psspy.py", line 3755, in case
psspy.CaseError: case Error: ierr=3

Python Exception raised!

I am not trying to rain on your parade because it was pretty neat you were able to create your own, just giving another method.

edit flag offensive delete link more

Comments

I use this method too, the `throwPsseExceptions` line should really be at the top of every script. It is frustrating that the ierr code they provide doesn't have the documentation string next to it like in @jsexauer example.

JervisW gravatar imageJervisW ( 2013-09-12 20:02:02 -0500 )edit
1

That is awesome @EBahr! Is that functionality documented anywhere? I feel like there is so much in psspy, but so little of it written down...

jsexauer gravatar imagejsexauer ( 2013-09-16 15:13:32 -0500 )edit
1

It is actually hiding in the very beginning of the API documentation under the Preface section.

EBahr gravatar imageEBahr ( 2013-09-16 17:49:31 -0500 )edit

It's very well hidden

JervisW gravatar imageJervisW ( 2013-09-28 02:35:24 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

[hide preview]

Question Tools

Stats

Asked: 2013-09-03 10:13:23 -0500

Seen: 1,175 times

Last updated: Sep 12 '13