以下代码提供了上述步骤的示例。构建解决方案将在项目的 bin 文件夹中创建一个新的 .dll。现在,此 .dll 可以作为软件包的一部分或通过导航到 File < Import Library... 以输入到 Dynamo 中
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
namespace PythonLibrary
{
public class PythonZT
{
// Unless a constructor is provided, Dynamo will automatically create one and add it to the library
// To avoid this, create a private constructor
private PythonZT() { }
// The method that executes the Python string
public static string executePyString(string pyString)
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Execute(pyString, scope);
// Return the value of the 'output' variable from the Python script below
var output = scope.GetVariable("output");
return (output);
}
}
}
Python 脚本将返回变量 output,这意味着我们在 Python 脚本中需要一个 output 变量。使用此样例脚本以在 Dynamo 中测试节点。如果您曾在 Dynamo 中使用过 Python 节点,则以下内容应该很熟悉。有关详细信息,请查看入门手册的 Python 部分。
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Collections.Generic;
using Autodesk.DesignScript.Runtime;
namespace PythonLibrary
{
public class PythonZT
{
private PythonZT() { }
[MultiReturn(new[] { "output1", "output2" })]
public static Dictionary<string, object> executePyString(string pyString)
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Execute(pyString, scope);
// Return the value of 'output1' from script
var output1 = scope.GetVariable("output1");
// Return the value of 'output2' from script
var output2 = scope.GetVariable("output2");
// Define the names of outputs and the objects to return
return new Dictionary<string, object> {
{ "output1", (output1) },
{ "output2", (output2) }
};
}
}
}