0

我正在尝试使代码从这个 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 应该运行,其他一切都应该在我单击按钮后运行。

我附上了用于初始化 Ansys 中的所有内容和用于生成 ui 的 xml 文件,以及主要的 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
4

2 回答 2

2

您在第 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

于 2021-04-15T08:14:53.993 回答
0

我使用了相同的代码,但我做了这些修改,它现在可以工作了。简而言之,您需要先定义“结果”变量,然后才能在其他函数中使用它

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

def CreateCustomPost(analysis):
    ExtAPI.Log.WriteMessage("clicked on CustomPost button")
    result=analysis.CreateResultObject("CustomPost")
于 2021-05-27T11:56:20.420 回答