Ansys ironpython行为不运行

2024-04-24 20:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让代码在youtube视频中从9-17分钟开始工作:https://www.youtube.com/watch?v=oX5hDU0Qg-Q

我写下了每一行代码,它应该可以工作,但是在打开Ansys时我会出现以下错误:

unexpected token 'ExtAPI' at line 69 in file C:\Program Files\ANSYS Inc\v202\Addins\ACT\extensions\ACT_NumPy_Ex3\main3.py: 
ExtAPI.Log.WriteMessage("Scalled Ux contour plotted from ACT_Numpy_Ex3 Extension")
index out of range: 1 
IndexOutOfRangeException 
at IronPython.Runtime.Operations.PythonOps.FixIndex(Int32 v, Int32 len) 
at IronPython.Runtime.List.get_Item(Int32 index) 
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1) 
at $3.(CodeContext $globalContext, FunctionCode $functionCode) in C:\Program Files\ANSYS Inc\v202\Addins\ACT\extensions\ACT_NumPy_Ex3\A_NumpyFun3.py:line 45 
at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx) 
at Ansys.ACT.Core.Extension.ReadScripts() 
Unable to find callback method 'oninit', named 'init', in python file.
Unable to find callback method 'onclick', named 'CreateCustomPost_1', in python file.

我知道第69行不应该产生错误,所以错误一定在其他地方。我也不明白最后两行错误是如何发生的,因为它们应该按预期工作

当打开Ansys时,只有初始化函数init应该运行,其他所有的都应该在我点击一个按钮后运行

我附上了xml文件,用于初始化Ansys中的所有内容和生成ui,以及主ironpython文件

<extension version="192" minorversion="0" name="ACT_NumPy_Ex3">
    <guid shortid="ACT_NumPy_Ex3">98V1CB96-4EEE-4DF2-AA62-EC8F9838543A</guid>
    <author>SanthoshM</author>
    <description> Asd
    </description>
    <script src="main3.py" compiled="true"/>
    <script src="A_NumpyFun3.py" compiled="true"/>
    <interface context="Mechanical">
        <images>images</images>
        <callbacks>
            <oninit>init</oninit>
        </callbacks>

        <toolbar name = "ACT_NumPy_Ex3" caption = "ACT_NumPy_Ex3">
            <entry name = "ACT_NumPy_Ex3" icon = "hand">
                <callbacks>
                    <onclick>CreateCustomPost</onclick>
                </callbacks>
            </entry>
        </toolbar>
    </interface>
    
    
        <simdata context ="Mechanical">
        
            <result name="CustomRes" version="1" caption="CustomNumPyRes" icon="hand" location="node" type="scalar" >
                <callbacks>
                    <evaluate>Manupulate</evaluate>
                </callbacks>
                
                <property name="Geometry" caption="Geometry" control="scoping"> </property>
                <property name="DispFactor" caption="DispFactor" control="float" default="5.0"> </property>
                <property name="InputFileName" caption="Input csv File Name" control="text" default="auto" readonly="true"> </property>
                <property name="OutputFileName" caption="Output csv File Name" control="text" default="auto" readonly="true"> </property>
                
            </result>
        
        </simdata>
        
</extension>
clr.AddReference("Ans.UI.Toolkit")
clr.AddReference("Ans.UI.Toolkit.Base")
import os
import subprocess
import units
from Ansys.UI.Toolkit import *

def init(context):
    ExtAPI.Log.WriteMessage("Intializing Numpy maniuplate ...")

def CreateCustomPost(analysis):
    analysis.CreateResultObject("CustomRes", ExtAPI.ExtensionManager.CurrentExtension)


def Manupulate(result, stepInfo, collector):
    step = stepInfo.Set
    analysis = result.Analysis
    reader = analysis.GetResultsata()
    reader.CurrentResultSet = step
    Disp=reader.GetResult("U")
    #DispUx=Disp.GetNoteValues(66)[0]
    mesh = analysis.MeshData
    
    WorkingdirName = analysis.WorkingDir
    InstallDir = ExtAPI.ExtensionManager.CurrentExtension.InstallDir
    OneUp=System.IO.Path.Combine(ExtAPI.DataModel.AnalysisList[0].WorkingDir,'..')
    TwoUp=System.IO.Path.Combine(OneUp, '..')
    ThreeUp=System.IO.Path.Combine(TwoUp, '..')
    UserFiles=System.IO.Path.Combine(ThreeUp, '..')
    
    AnsResfilesname=ExtAPI.ExtensionManager.CurrentExtension.Name + "DispUx_Input.csv" #Ansys raw results
    ManResfilename=ExtAPI.ExtensionManager.CurrentExtension.Name + "DispUx_Output.csv" #Results manuplted with Numpy
    
    ipfile=os.path.join(UserFiles,AnsResfilename)
    opfile=os.path.join(UserFiles,ManResfilename)
    #ExtAPI.Log.WriteMessage(ipfile)
    #ExtAPI.Log.WriteMessage(opfile)
    
    fl=open(ipfile,"w")
    
    nodeIds = collector.Ids
    ExtAPI.Log.WriteMessage(str(nodeIds))
    for nId in nodeIds:
        #ExtAPI.Log.WriteMessage (Str(nId) +"'''"+str(Disp.GetNodeValues(nId)[0]))
        fl.write(str(nId)+","+str(Disp.GetNodeValues(nId)[0])+"\n")
    fl.close()
    
    scaleFactor=result.Properties["DispFactor"].Value
    result.Properties["InputFileName"].Value =AnsResfilesname
    result.Properties["OutputFileName"].Value =ManResfilename
    
    callCpython(scaleFactor, UserFiles, ipfile,opfile)
    
    import csv
    resfile=opfile
    reader=csv.reader(open(resfile, 'rb'),quoting=csv.QOUTE_NONNUMERIC)
    NodeNos = next(reader)
    ScaledUxs=next(reader)
    a=int(NodeNos[1])
    b=ScaledUxs[1]
    ExtAPI.Log.WriteMessage(a.GetType().ToString())
    ExtAPI.Log.WriteMessage(b.GetType().ToString())
    userUnit = ExtAPI.DataModel.CurrentUnitFromQauntityName("Lenght")
    DispFactor = units.ConvertUnit(1, userUnit, "m")
    
    for id in collector.Ids:
        collector.SetValues(int(NodeNos[NodeNos.index(id)], {ScaledUxs[NodeNos.index(id)] * DispFactor})  # The value to display
    
    ExtAPI.Log.WriteMessage("Scalled Ux contour plotted from ACT_Numpy_Ex3 Extension")
    return True
    

def callCpython(scaleFactor,UserFiles,ipfile,opfile,input=None):

    InstallDir = ExtAPI.ExtensionManager.CurrentExtension.InstallDir
    python372=r"C:\Users\Martin\AppData\Local\Programs\Python\Python39\python.exe" ### Your Cpython .exe file location
    PyinputFile=os.path.join(InstallDir, "A_NumpyFun3.py")
    
    ExtAPI.Log.WriteMessage(str(scaleFactor))
    
    process=subprocess.Popen([python372,PyinputFile,UserFiles,ipfile,opfile,str(scaleFactor)])
    process.wait()
    
    return True

Tags: csvnameinnumpylogpropertyresultact
2条回答

我使用了相同的代码,但我做了这些修改,现在它工作了。 简而言之,在其他函数中使用“result”变量之前,需要先定义它

def __init__(context):
    ExtAPI.Log.WriteMessage("initiating Scipy manipulate...")
    pass  

def CreateCustomPost(analysis):
    ExtAPI.Log.WriteMessage("clicked on CustomPost button")
    result=analysis.CreateResultObject("CustomPost")

第67行缺少一个右括号。目前案文如下:

collector.SetValues(int(NodeNos[NodeNos.index(id)], {ScaledUxs[NodeNos.index(id)] * DispFactor})  # The value to display

它需要阅读

collector.SetValues(int(NodeNos[NodeNos.index(id)]), {ScaledUxs[NodeNos.index(id)] * DispFactor})  # The value to display

您在int上缺少一个右括号

相关问题 更多 >