Author Topic: [IronPython] Simple script engine for AutoCAD  (Read 2823 times)

0 Members and 1 Guest are viewing this topic.

MickD

  • King Gator
  • Posts: 3619
  • (x-in)->[process]->(y-out) ... simples!
[IronPython] Simple script engine for AutoCAD
« on: May 07, 2009, 08:32:38 PM »
Here's a very simple example of setting up a scripting engine for IronPython inside AutoCAD.

I won't explain too much as there's not much to tell as the code says it all really, it's just useful for testing and running simple Ipy scripts.

the one adavantage of using this system (creating an engine each run) is you can edit your script and re-run it without unloading the .net dll, if you use commands you may have trouble with this.

Anyway, here's the C# code and I'll attach the dll for those who just want to use the engine and start scripting.
Of course, you need IronPython 1.1.2 installed and ref'd into your solution.


Commands.cs
Code: [Select]
using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

[assembly: CommandClass(typeof(IPyCADv1._1.Commands))]

namespace IPyCADv1._1
{
    public class Commands
    {
        public Commands()
        {

        }
        // Define Command
        [CommandMethod("IPYRUN")]
        static public void IPyRun()
        {
            // get the script name from the user:
            Editor ed = acadApp.DocumentManager.MdiActiveDocument.Editor;
            PromptResult res = ed.GetString("\nEnter script file name (incl. '.py' extension): ");
            string script = res.StringResult;
            // Put your command code here
            IPyEngine e = new IPyEngine();
            e.IPyRun(script);
        }
    }
}

IpyEngine.cs
Code: [Select]
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IronPython.Hosting;
using IronPython.Compiler;

namespace IPyCADv1._1
{
    class IPyEngine
    {
        private PythonEngine engine;
        public IPyEngine()
        {
            engine = new PythonEngine();
        }

        public void IPyRun(string script)
        {
            try
            {
                engine.ExecuteFile(script);
            }
            catch (Exception exc)
            {
                MessageBox.Show("\n" + exc.ToString());
            }
        }
    }
}

To use the dll. create a file somewhere to save your scripts and the dll and you should be right to go. You may also need to copy the other dlls as per the attached image. <edit>oops just noticed a dll no one will have in there - the IpyForm.dll is a form I made in C# to import and derive from in Ipy, this is the easiest way to create a form using a gui rather than code.
« Last Edit: May 08, 2009, 03:12:27 AM by MickD »
"Short cuts make long delays,' argued Pippin.”
J.R.R. Tolkien