What's new

Alibre Python shell addon source code and installer

stepalibre

Alibre Super User
I forked the popular opensource IronLab Python Shell project (see links) for Alibre Design. If you're interested in the project the source code is available. I can explain how it works including the Alibre integration code, so please feel free to ask. Viewing the code should be enough to understand the basic concept the integration code is straightforward.

It is currently in a working state as shown below. However, because the addon uses AlibreX and Alibre Script directly you will need to navigate through IronPython and .NET type conversion issues. The imports and references I have inside the examples aren't best practices and can be removed if they're not needed.

1710900210776.png1710393120430.png1710393401921.png

 
Last edited:

stepalibre

Alibre Super User
I published an installer to make it easy to install:

1710884661958.png



Any questions or comments related to code can be asked here. I don't have any plans to add more to the addon, however I use it daily and will fix bugs. The installer was tested on 3 machines using Alibre Design 27.0.1.27039.

The only feature I want to add is a scripts database or a way to store scripts to re-run or reload from a list. Only a vague idea at the moment...
 
Last edited:

stepalibre

Alibre Super User
More Information:

I've spent 3-4 months using the addon, and with its limited error handling, it is stable. The nature of a console interface is to catch and display failed code gracefully. Please inform me of any issues you find. The addon should run under any actively supported version of Alibre Design.

I'll update the README when I have time later.
 

stepalibre

Alibre Super User
Download Information:

Similar to the suspicious download warnings seen with @bolsover's GitHub.com releases, this is due to the installer and ZIPs being unsigned. I provide downloads in EXE, 7Z, and ZIP formats.

1710899191404.png

Standard unblocking required.

1710899216668.png
 

stepalibre

Alibre Super User
I'll cleanup and add more examples to the repo later, but for now...

Example Code: This is plain IronPython (Python 2.7) code importing, referencing libraries, calling classes and methods, very standard stuff.

AlibreX Python Script:
Python:
import sys
import clr
clr.AddReference('System.Runtime.InteropServices')
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
from System.Runtime.InteropServices import Marshal
alibre = Marshal.GetActiveObject("AlibreX.AutomationHook")
root = alibre.Root
session = root.TopmostSession
objADPartSession = session
b = objADPartSession.Bodies
verts = b.Item(0).Vertices
listA = []
def printpoint(x, y, z):
    print("{0} , {1} , {2}".format(x, y, z))
    listA.append("{0} , {1} , {2}".format(x, y, z))
for i in range(verts.Count):
    vert = verts.Item(i)
    point = vert.Point
    printpoint(point.X, point.Y, point.Z)
from System.Windows.Forms import MessageBox, MessageBoxButtons
list_str = ', '.join(map(str, listA))
MessageBox.Show(list_str, "AlibreX Python Script", MessageBoxButtons.OK)

Alibre Script:
Python:
import sys
import clr
clr.AddReference("alibre-api")
clr.AddReference("AlibreScriptAddOn")
clr.AddReference('System.Runtime.InteropServices')
from System.Runtime.InteropServices import Marshal
from com.alibre.automation import *
from AlibreScript.API import *
# HERE IS ONE METHOD TO GET THE SESSION
alibre = Marshal.GetActiveObject("AlibreX.AutomationHook")
root = alibre.Root
myPart = Part(root.TopmostSession)

# ALIBRE SCRIPT CODE
Win = Windows()
Win.InfoDialog('This code is from Alibre Script.', myPart.FileName)
Win.ErrorDialog('This code is from Alibre Script!', myPart.LastAuthor)
print(Win.QuestionDialog('This code is from Alibre Script?', myPart.CreatedBy))

Alibre Script & AlibreX Python Code:
Python:
import sys
import clr
sys.path.append("C:\Program Files\Alibre Design 27.0.1.27039\Program")
sys.path.append("C:\Program Files\Alibre Design 27.0.1.27039\Program\Addons\AlibreScript")
clr.AddReference("AlibreX")
clr.AddReference("AlibreScriptAddOn")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
import AlibreX
sys.path.append("C:\\PROGRAM FILES\\Alibre Design 27.0.1.27039\\PROGRAM\\ADDONS\\ALIBRESCRIPT\\PythonLib")
sys.path.append("C:\\PROGRAM FILES\\Alibre Design 27.0.1.27039\\PROGRAM\\ADDONS\\ALIBRESCRIPT")
sys.path.append("C:\\PROGRAM FILES\\Alibre Design 27.0.1.27039\\PROGRAM\\ADDONS\\ALIBRESCRIPT\\PythonLib\\site-packages")
import AlibreScript
from AlibreScript.API import *
clr.AddReference('System.Runtime.InteropServices')
from System.Runtime.InteropServices import Marshal
alibre = Marshal.GetActiveObject("AlibreX.AutomationHook")
root = alibre.Root
myPart = Part(root.TopmostSession)
session = root.Sessions.Item(0)
objADPartSession = session
print(session.FilePath)
print(objADPartSession.Bodies.Count)
b = objADPartSession.Bodies
verts = b.Item(0).Vertices
print(verts.Count)
def printpoint(x, y, z):
   print("{0} , {1} , {2}".format(x, y, z)) 
for i in range(verts.Count):
   vert = verts.Item(i)
   point = vert.Point
   printpoint(point.X, point.Y, point.Z)  # Calls the printpoint function defined later
def printpoint(x, y, z):
   print("{0} , {1} , {2}".format(x, y, z))
Win = Windows()
Win.InfoDialog('This code is from Alibre Script.', myPart.FileName)
Win.ErrorDialog('This code is from Alibre Script!', myPart.LastAuthor)
print(Win.QuestionDialog('This code is from Alibre Script?', myPart.CreatedBy))

1710902462448.png
 

DavidJ

Administrator
Staff member
Stephen - sorry if I'm being particularly stupid, but I don't understand from your above posts what this add-on is for, nor why an Alibre user might want to install it.

Could you maybe add a simple explanation in layman's terms...?
 

stepalibre

Alibre Super User
No problem at all David.

The addon is essentially the same as the Alibre Script addon text editor and console windows. The difference is that this is a dedicated window which does not require the Alibre Script addon to be loaded in order to work with Alibre Script code. You can write Alibre Script, AlibreX or any IronPython (Python 2.7) program directly in the shell interface. It includes basic autocomplete and other standard features that are based on the IronLab project as mentioned above. Programs you write can have code that crosses part and assembly files allowing you to have scripts that are connected and can get or set data from parts to and from assemblies or whatever you want. The main drawback of Alibre Script code is that the Alibre Script addon handles a lot of functionality not present in the Alibre Python Shell. You are interacting with the library in a more direct manner which can be more advanced.

I use it all the time for all sorts of tasks. Here are a few: (My work is all based on my local file system and software with hard coded paths. I'm working on cleaning them up to make it easier to share and maintain.)
- Exporting and Importing files
- Creating features/sketches from outside data
- Get/Set parameter values
- Changing configurations
- Rhino and MoI subprocess tools
- Forcing save and regeneration
- Running my tools written in .NET

You can use the Alibre Script addon alongside the Alibre Python Shell. Alibre Design can be minimized while you interact with the addon, many possibilities.

1710924267674.png

This is a topic that involves both Add-On development (AlibreX) and Alibre Script. Anything can be discussed here, so I'm never quite sure where to post.
 

albie0803

Alibre Super User
You posted while I was still typing

I think I know what it does but it definitely needs a "Getting Started" manual with detailed instructions on what it does, why we should use it, what the differences are and when to use one or the other, starting it, what NEEDS to be included and what is "built in" and making a simple script.

For programmers, it's most likely quite obvious what it does but for those of us trying to dabble in the scripting option, we need help!
 

Stu3d

Senior Member
I use MicroPython in Thonny for programming Raspberry Pi Pico micrcontrollers but have absolutely no idea where to start with IronPython, AI etc. A step by step getting started tutorial would be great as I would really like to experiment with this especially given all the hard work you put in to it.
 

DavidJ

Administrator
Staff member
I sort of get it - even simpler explanation would be good. I'm still not very clear on the 'Why?' aspect.

Is it 'just' a free-floating window in which Scripts can be written ?
 

NateLiquidGravity

Alibre Super User
It's probably not for most users. Unless you have already hit a technical limit in programming in Alibre Script you wouldn't see much benefit - and if you did hit that limit you would understand what this is without an in depth help file.
 

stepalibre

Alibre Super User
I sort of get it - even simpler explanation would be good. I'm still not very clear on the 'Why?' aspect.

Is it 'just' a free-floating window in which Scripts can be written ?
The "Why" is the same as Alibre Script and programming in general. It's a console/shell which is not the most user friendly, but I do believe it is easier to use over a full text editor or an IDE.

The key benefit is that it is a dedicated window instead of being attached to a specific Alibre Design window.

With this class you can call the export_part_to_sat function to quickly export a part to sat or any format:
Usage:
Code:
IronPython 2.7.12 (2.7.12.1000)
[.NETFramework,Version=v4.5 on .NET Framework 4.8.9181.0 (64-bit)]
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> tools = AlibrePythonUtils()
>>> tools.export_part_to_sat("C:\Users\steph\Desktop\output-sat-test-50.sat")
Code:
Python:
import clr
clr.AddReference("AlibreScriptAddOn")
clr.AddReference('System.Runtime.InteropServices')
from System.Runtime.InteropServices import Marshal
from AlibreScript.API import *

class AlibrePythonUtils:
    def __init__(self):
        """Initialize the Alibre Python Utils session."""
        try:
            self.alibre = Marshal.GetActiveObject("AlibreX.AutomationHook")
            self.root = self.alibre.Root
        except Exception as e:
            print "Failed to initialize Alibre Python Utils: %s" % e
            self.alibre = None
            self.root = None

    def export_part_to_sat(self, filename, sat_version=7, save_colors=False):
        """
        Exports the active part in Alibre Design to an SAT file.

        Parameters:
        - filename: The path where the SAT file will be saved.
        - sat_version: Version of the SAT format to use. Defaults to 7.
        - save_colors: Whether to export colors. Defaults to False (binary format).
        """
        if not self.alibre or not self.root:
            print "Alibre Python Utils is not initialized."
            return

        try:
            myPart = Part(self.root.TopmostSession)
            myPart.ExportSAT(filename, sat_version, save_colors)
            print "Successfully exported the part to %s" % filename
        except Exception as e:
            print "An error occurred during export: %s" % e

It's probably not for most users. Unless you have already hit a technical limit in programming in Alibre Script you wouldn't see much benefit - and if you did hit that limit you would understand what this is without an in depth help file.
I posted the addon under "Add-on Development" rather than "General Discussion" or "Using Alibre Design" because it requires existing programming knowledge or is intended for those who are willing to learn programming. The code is available for anyone who wants to create their own version or learn from it.
 
Last edited:

simonb65

Alibre Super User
The key benefit is that it is a dedicated window instead of being attached to a specific Alibre Design window.
You do realise that AlibreScript was originally a separate Add-on until Alibre integrated it into the application to make it easier for users? What you have done just seems like a step backwards! Just my opinion. If you just want a floating window, suggest to Alibre that the current windows would be better dockable.
 

DavidJ

Administrator
Staff member
I've previously used an empty Alibre part file solely as a Script container, which then manipulates other Alibre files (in headless mode for example).

I only 'dabble' in Alibre Script, so can't really comment on if this add-on would be helpful. I need to concentrate on improving my knowledge of Python, and the Alibre specific stuff.
 

Stu3d

Senior Member
In the 2d cad package I use there is a script feature which enables a series of commands, distances, angles, text etc to be strung together to create shortcuts, hatch patterns, small drawing elements etc.
The script can be assigned to a keyboard shortcut so it's a bit like AutoHot Key but specific to the cad package. Hit a 2 or 3 key combination and the script is run.
Every single command in the software can be used which makes pretty much anything possible.

I accept Script in Alibre is likely a lot more powerful but am I right in assuming Script has to be lauched to open the console, then a script selected (eg Examples>Mechanical>Gear Generator), click Run and then enter parameters?
Is there a way to have a keyboard shortcut that launches the Gear Generator with one key press?
I guess there are also a lot of settings internal to commands that can't be accessed in Script, for example changing from sketch figure to reference figure in project to sketch

I appreciate the script in my 2d package is a basic shortcut feature whereas I assume Script in Alibre is more a programming language, based on Python?
 

stepalibre

Alibre Super User
You do realise that AlibreScript was originally a separate Add-on until Alibre integrated it into the application to make it easier for users? What you have done just seems like a step backwards! Just my opinion. If you just want a floating window, suggest to Alibre that the current windows would be better dockable.
The addon is a tool in a toolbox. Some of us can make do with a 5-piece screwdriver set, some prefer a 12-piece screwdriver set, and some require a 25-piece screwdriver set.
Alibre is more a programming language, based on Python?
Alibre Script is IronPython 2.7 which is Python 2.7.
I accept Script in Alibre is likely a lot more powerful but am I right in assuming Script has to be lauched to open the console, then a script selected (eg Examples>Mechanical>Gear Generator), click Run and then enter parameters?
Is there a way to have a keyboard shortcut that launches the Gear Generator with one key press?
I'll address these later.
 
Top