Last active
October 26, 2020 22:44
-
-
Save jsexauer/6425120 to your computer and use it in GitHub Desktop.
Decorator for PSSE's psspy module functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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
See https://psspy.org/psse-help-forum/question/1107/raise-psspy-ierr-as-python-exception/ for additional discussion