【发布时间】:2020-02-13 19:03:31
【问题描述】:
我的目标是在 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 脚本?
非常感谢,
【问题讨论】:
-
请注意,您引用的博文来自 2009 年,最新的 IronPython 版本已经有一年多的历史了,并且是针对 Python 2 标准编写的。 Python 2 has been sunsetted 由官方维护 Python 的组织提供,因此该组织将来不会更新其标准。
标签: c# python dll ironpython