简体   繁体   English

Python PSS / E将输出作为变量

[英]Python PSS/E get output as variable

I am power engineer and I often use python in PSS/E program. 我是电源工程师,我经常在PSS / E程序中使用python。 I am stacked and I want your help as programmers. 我堆积如山,我希望得到您作为程序员的帮助。 I have this small code: 我有这个小代码:

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)

Code redirect.psse2py() prints the program report in Console. 代码redirect.psse2py()在控制台中打印程序报告。 Can you help me to get those outputs as variable? 您能帮我把这些输出作为变量吗?

Given I don't know much about PSSE, you can try the following: 鉴于我对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()

My favorite solution so far is based on @JF Sebastian answer Redirect stdout to a file in Python? 到目前为止,我最喜欢的解决方案基于@JF Sebastian答案将stdout重定向到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. psspy.report_output()使用psspy.report_output()和相关函数似乎是最好的选择,但是它们有些痛苦,因为您只能写入文件,而不能写入StringIO缓冲区。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM