我的目标是在Autocad中运行python脚本。为此,我使用IronPython 2.7.9创建一个NET API。遇到的困难是Autocad使用自定义属性来标识命令,因此我的计划是使用此代码来选择和加载Python脚本:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
namespace PythonLoader
{
public class CommandsAndFunctions
{
[CommandMethod("-PYLOAD")]
public static void PythonLoadCmdLine()
{
PythonLoad(true);
}
[CommandMethod("PYLOAD")]
public static void PythonLoadUI()
{
PythonLoad(false);
}
public static void PythonLoad(bool useCmdLine)
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
short fd =
(short)Application.GetSystemVariable("FILEDIA");
// As the user to select a .py file
PromptOpenFileOptions pfo =
new PromptOpenFileOptions(
"Select Python script to load"
);
pfo.Filter = "Python script (*.py)|*.py";
pfo.PreferCommandLine =
(useCmdLine || fd == 0);
PromptFileNameResult pr =
ed.GetFileNameForOpen(pfo);
// And then try to load and execute it
if (pr.Status == PromptStatus.OK)
ExecutePythonScript(pr.StringResult);
}
[LispFunction("PYLOAD")]
public ResultBuffer PythonLoadLISP(ResultBuffer rb)
{
const int RTSTR = 5005;
Document doc =
Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
if (rb == null)
{
ed.WriteMessage("\nError: too few arguments\n");
}
else
{
// We're only really interested in the first argument
Array args = rb.AsArray();
TypedValue tv = (TypedValue)args.GetValue(0);
// Which should be the filename of our script
if (tv != null && tv.TypeCode == RTSTR)
{
// If we manage to execute it, let's return the
// filename as the result of the function
// (just as (arxload) does)
bool success =
ExecutePythonScript(Convert.ToString(tv.Value));
return
(success ?
new ResultBuffer(
new TypedValue(RTSTR, tv.Value)
)
: null);
}
}
return null;
}
private static bool ExecutePythonScript(string file)
{
// If the file exists, let's load and execute it
// (we could/should probably add some more robust
// exception handling here)
bool ret = System.IO.File.Exists(file);
if (ret)
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(file);
}
return ret;
}
}
}
在本文中,作者说,我需要构建该脚本的.dll并添加对以下内容的引用:
IronPython.dll
IronPythonmodules.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Core.dll
和“标准引用”
acmgd.dll
acdbmgd.dll
我已经下载了一个反编译器,并开始查看这些.dll的代码,当然还有很多不同的代码需要查看。如何找出上面发布的PYLOAD脚本的引用的位置,以便可以开始在Autocad中执行python脚本?
非常感谢,
首先,您需要编译发布到程序集中的.NET代码(例如,将其称为“ PythonLoader.dll”)。使用PythonLoader代码创建程序集后,您可以按照一组指令here加载程序集,从而在PYLOAD IronPython脚本中引用该程序集。作者提供的示例都使用了clr.AddReferenceToFileAndPath
,所以我也可能会从中开始。
>>> import clr
>>> clr.AddReferenceToFileAndPath(path_to_your_assembly)
请注意,您需要将.NET代码编译为与IronPython环境所针对的框架版本相匹配的.NET Core或.NET Framework版本。 (从the IronPython 2.7.9 source开始,它看起来像是针对.NET Framework 4.5,.NET Core 2.0和.NET Core 2.1。)