1

我是电力工程师,我经常在 PSS/E 程序中使用 python。我很累,我希望你作为程序员的帮助。我有这个小代码:

import os,sys

PSSE_LOCATION = r"C:\Program Files\PTI\PSSE33\PSSBIN"
sys.path.append(PSSE_LOCATION)
os.environ['PATH'] = os.environ['PATH'] + ';' +  PSSE_LOCATION

import psspy
import redirect
redirect.psse2py()

#--------------------------------
# PSS/E Saved case

CASE = r"""D:\xxx\Desktop\TESTING\SUMMAX.sav"""

if __name__ == '__main__':
    psspy.psseinit(2000)
    psspy.case(CASE)
    psspy.fnsl(
        options1=0, # disable tap stepping adjustment.
        options5=0, # disable switched shunt adjustment.
    )
    psspy.fdns([0,0,0,1,1,0,99,0])
    psspy.area_2(0,1,1)

代码redirect.psse2py()在控制台中打印程序报告。你能帮我把这些输出作为变量吗?

4

2 回答 2

1

鉴于我对 PSSE 不太了解,您可以尝试以下方法:

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()
于 2014-09-02T10:35:17.813 回答
0

到目前为止,我最喜欢的解决方案是基于@JF Sebastian 回答Redirect stdout to a file in Python? .

起初使用psspy.report_output()和 相关函数似乎是最好的选择,但它们有点痛苦,因为您只能写入文件而不能写入StringIO缓冲区。

这是一个完整的例子:

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

打印:

< snip PSSE init copyright header>
before redirect
after redirect
var: 123xxx(report)
abcyyy(alert)
foobar(progress)
于 2015-02-12T19:54:43.037 回答