Skip to content

Instantly share code, notes, and snippets.

@jsexauer
Last active October 26, 2020 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jsexauer/6425120 to your computer and use it in GitHub Desktop.
Save jsexauer/6425120 to your computer and use it in GitHub Desktop.
Decorator for PSSE's psspy module functions
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
@jsexauer
Copy link
Author

jsexauer commented Sep 3, 2013

@jtrain
Copy link

jtrain commented Sep 11, 2013

This is great @jsexauer. I normally run my scripts with

psspy.throwPsseExceptions = True

enabled near the top of the script. With a few small changes, I managed to get your code working with Psse exception types.

Here is the version for when using psspy.throwPsseExceptions = True
https://gist.github.com/jtrain/6519794#file-raisepsspyerror-py

@jsexauer
Copy link
Author

That is a good synergy of my method and the psspy.throwPsseExceptions method. I didn't know about psspy.throwPsseExceptions when I did wrote this; its a cool feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment