Python PSS/E get output as variable

↘锁芯ラ 提交于 2019-12-02 06:14:43

Given I don't know much about PSSE, you can try the following:

import sys
import io

out, err = io.StringIO(), io.StringIO()
sys.stdout = out
sys.stderr = err

# rest of your code here

# once your code is finished

results = out.getvalue()
errors = err.getvalue()
chip

My favorite solution so far is based on @J.F Sebastian answer Redirect stdout to a file in Python?.

Using the psspy.report_output() and related functions at first seemed like the best option, but they are a little painful because you can only write to a file and not a StringIO buffer.

Here is a complete example:

import contextlib
import sys

# Auto-magically setup PSSE environment.  
# You can do this step the hard way if you want
import pssepath
pssepath.add_pssepath()

import psspy
import redirect
redirect.psse2py()
psspy.psseinit(50000)

@contextlib.contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value


import StringIO
f = StringIO.StringIO()
print "before redirect"
with redirect_stdout(f):
    psspy.report('123xxx(report)')
    psspy.alert('abcyyy(alert)')
    psspy.progress('foobar(progress)')
    f.seek(0)
    var = f.read()

print "after redirect"
print "var: %s" % var

which prints:

< snip PSSE init copyright header>
before redirect
after redirect
var: 123xxx(report)
abcyyy(alert)
foobar(progress)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!