This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...

A typical InitGui.py file

Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.

classScriptWorkbench(Workbench):MenuText="Scripts"defInitialize(self):importScripts# assuming Scripts.py is your modulelist=["Script_Cmd"]# That list must contain command names, that can be defined in Scripts.pyself.appendToolbar("My Scripts",list)Gui.addWorkbench(ScriptWorkbench())

A typical module file

This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.

Import a new filetype

Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:

This line must be added to the InitGui.py file to add the new file extension to the list:

# Assumes Import_Ext.py is the file that has the code for opening and reading .ext filesFreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")

Then in the Import_Ext.py file:

defopen(filename):doc=App.newDocument()# here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objectsdoc.recompute()

To export your document to some new filetype works the same way, except that you use:

FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

Adding a line

A line simply has 2 points.

importPart,PartGuidoc=App.activeDocument()# add a line element to the document and set its points l=Part.Line()l.StartPoint=(0.0,0.0,0.0)l.EndPoint=(1.0,1.0,1.0)doc.addObject("Part::Feature","Line").Shape=l.toShape()doc.recompute()

Adding a polygon

A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

importPart,PartGuidoc=App.activeDocument()n=list()# create a 3D vector, set its coordinates and add it to the list v=App.Vector(0,0,0)n.append(v)v=App.Vector(10,0,0)n.append(v)#... repeat for all nodes # Create a polygon object and set its nodes p=doc.addObject("Part::Polygon","Polygon")p.Nodes=ndoc.recompute()

Adding and removing an object to a group

doc=App.activeDocument()grp=doc.addObject("App::DocumentObjectGroup","Group")lin=doc.addObject("Part::Feature","Line")grp.addObject(lin)# adds the lin object to the group grpgrp.removeObject(lin)# removes the lin object from the group grp

Note: You can even add other groups to a group...

Adding a Mesh

importMeshdoc=App.activeDocument()# create a new empty meshm=Mesh.Mesh()# build up box out of 12 facetsm.addFacet(0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0)m.addFacet(0.0,0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0)m.addFacet(0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0)m.addFacet(0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0)m.addFacet(0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0)m.addFacet(0.0,0.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0)m.addFacet(0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0)m.addFacet(0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0)m.addFacet(0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0)m.addFacet(0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0)m.addFacet(1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0)m.addFacet(1.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0)# scale to a edge langth of 100m.scale(100.0)# add the mesh to the active documentme=doc.addObject("Mesh::Feature","Cube")me.Mesh=m

Adding an arc or a circle

importPartdoc=App.activeDocument()c=Part.Circle()c.Radius=10.0f=doc.addObject("Part::Feature","Circle")# create a document with a circle feature f.Shape=c.toShape()# Assign the circle shape to the shape property doc.recompute()

Accessing and changing representation of an object

Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...

gad=Gui.activeDocument()# access the active document containing all # view representations of the features in the# corresponding App document v=gad.getObject("Cube")# access the view representation to the Mesh feature 'Cube' v.ShapeColor# prints the color to the console v.ShapeColor=(1.0,1.0,1.0)# sets the shape color to white

Observing mouse events in the 3D viewer via Python

The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.

Manipulate the scenegraph in Python

It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.

frompivy.coinimport*# load the pivy moduleview=Gui.ActiveDocument.ActiveView# get the active viewerroot=view.getSceneGraph()# the root is an SoSeparator noderoot.addChild(SoCube())view.fitAll()

The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python.
However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with

type=SoType.fromName("SoFCSelection")node=type.createInstance()

Adding and removing objects to/from the scenegraph

Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):

Saves the sceneGraph with a rotation in a series of 36 files in the X Y Z axis

importmathimporttimefromFreeCADimportBasefrompivyimportcoinsize=(1000,1000)dirname="C:/Temp/animation/"steps=36angle=2*math.pi/stepsmatX=Base.Matrix()matX.rotateX(angle)stepsX=Base.Placement(matX).RotationmatY=Base.Matrix()matY.rotateY(angle)stepsY=Base.Placement(matY).RotationmatZ=Base.Matrix()matZ.rotateZ(angle)stepsZ=Base.Placement(matZ).Rotationview=Gui.ActiveDocument.ActiveViewcam=view.getCameraNode()rotCamera=Base.Rotation(*cam.orientation.getValue().getValue())# this sets the lookat point to the center of circumsphere of the global bounding boxview.fitAll()# the camera's position, i.e. the user's eye pointposition=Base.Vector(*cam.position.getValue().getValue())distance=cam.focalDistance.getValue()# view directionvec=rotCamera.multVec(Base.Vector(0,0,-1))# this is the point on the screen the camera looks at# when rotating the camera we should make this point fixlookat=position+vec*distance# around x axisforiinrange(steps):rotCamera=stepsX.multiply(rotCamera)cam.orientation.setValue(*rotCamera.Q)vec=rotCamera.multVec(Base.Vector(0,0,-1))pos=lookat-vec*distancecam.position.setValue(pos.x,pos.y,pos.z)Gui.updateGui()time.sleep(0.3)view.saveImage(dirname+"x-%d.png"%i,*size)# around y axisforiinrange(steps):rotCamera=stepsY.multiply(rotCamera)cam.orientation.setValue(*rotCamera.Q)vec=rotCamera.multVec(Base.Vector(0,0,-1))pos=lookat-vec*distancecam.position.setValue(pos.x,pos.y,pos.z)Gui.updateGui()time.sleep(0.3)view.saveImage(dirname+"y-%d.png"%i,*size)# around z axisforiinrange(steps):rotCamera=stepsZ.multiply(rotCamera)cam.orientation.setValue(*rotCamera.Q)vec=rotCamera.multVec(Base.Vector(0,0,-1))pos=lookat-vec*distancecam.position.setValue(pos.x,pos.y,pos.z)Gui.updateGui()time.sleep(0.3)view.saveImage(dirname+"z-%d.png"%i,*size)

Adding custom widgets to the interface

You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PyQt4.

The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):

classmyWidget_Ui(object):defsetupUi(self,myWidget):myWidget.setObjectName("my Nice New Widget")myWidget.resize(QtCore.QSize(QtCore.QRect(0,0,300,100).size()).expandedTo(myWidget.minimumSizeHint()))# sets size of the widgetself.label=QtGui.QLabel(myWidget)# creates a labelself.label.setGeometry(QtCore.QRect(50,50,200,24))# sets its sizeself.label.setObjectName("label")# sets its name, so it can be found by namedefretranslateUi(self,draftToolbar):# built-in QT function that manages translations of widgetsmyWidget.setWindowTitle(QtGui.QApplication.translate("myWidget","My Widget",None,QtGui.QApplication.UnicodeUTF8))self.label.setText(QtGui.QApplication.translate("myWidget","Welcome to my new widget!",None,QtGui.QApplication.UnicodeUTF8))

Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:

app=QtGui.qAppFCmw=app.activeWindow()# the active qt window, = the freecad window since we are inside itmyNewFreeCADWidget=QtGui.QDockWidget()# create a new dckwidgetmyNewFreeCADWidget.ui=myWidget_Ui()# load the Ui scriptmyNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget)# setup the uiFCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget)# add the widget to the main window

Adding a Tab to the Combo View

The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.

# create new Tab in ComboViewfromPySideimportQtGui,QtCore#from PySide import uicdefgetMainWindow():"returns the main window"# using QtGui.qApp.activeWindow() isn't very reliable because if another# widget than the mainwindow is active (e.g. a dialog) the wrong widget is# returnedtoplevel=QtGui.qApp.topLevelWidgets()foriintoplevel:ifi.metaObject().className()=="Gui::MainWindow":returniraiseException("No main window found")defgetComboView(mw):dw=mw.findChildren(QtGui.QDockWidget)foriindw:ifstr(i.objectName())=="Combo View":returni.findChild(QtGui.QTabWidget)elifstr(i.objectName())=="Python Console":returni.findChild(QtGui.QTabWidget)raiseException("No tab widget found")mw=getMainWindow()tab=getComboView(getMainWindow())tab2=QtGui.QDialog()tab.addTab(tab2,"A Special Tab")#uic.loadUi("/myTaskPanelforTabs.ui",tab2)tab2.show()#tab.removeTab(2)

Getting the HTML contents of an opened webpage

Retrieve and use the coordinates of 3 selected points or objects

# -*- coding: utf-8 -*-# the line above to put the accentuated in the remarks# If this line is missing, an error will be returned# extract and use the coordinates of 3 objects selectedimportPart,FreeCAD,math,PartGui,FreeCADGuifromFreeCADimportBase,Consolesel=FreeCADGui.Selection.getSelection()# " sel " contains the items selectediflen(sel)!=3:# If there are no 3 objects selected, an error is displayed in the report view# The \r and \n at the end of line mean return and the newline CR + LF.Console.PrintError("Select 3 points exactly\r\n")else:points=[]forobjinsel:points.append(obj.Shape.BoundBox.Center)forptinpoints:# display of the coordinates in the report viewConsole.PrintMessage(str(pt.x)+"\r\n")Console.PrintMessage(str(pt.y)+"\r\n")Console.PrintMessage(str(pt.z)+"\r\n")Console.PrintMessage(str(pt[1])+"\r\n")

List all objects

# -*- coding: utf-8 -*-importFreeCAD,Draft# List all objects of the documentdoc=FreeCAD.ActiveDocumentobjs=FreeCAD.ActiveDocument.Objects#App.Console.PrintMessage(str(objs) + "\n")#App.Console.PrintMessage(str(len(FreeCAD.ActiveDocument.Objects)) + " Objects" + "\n")forobjinobjs:a=obj.Name# list the Name of the object (not modifiable)b=obj.Label# list the Label of the object (modifiable)try:c=obj.LabelText# list the LabeText of the text (modifiable)App.Console.PrintMessage(str(a)+" "+str(b)+" "+str(c)+"\n")# Displays the Name the Label and the textexcept:App.Console.PrintMessage(str(a)+" "+str(b)+"\n")# Displays the Name and the Label of the object#doc.removeObject("Box") # Clears the designated object

List the dimension give the name of object

Function resident with the mouse click action

Here with SelObserver on a object select

# -*- coding: utf-8 -*-# causes an action to the mouse click on an object# This function remains resident (in memory) with the function "addObserver(s)"# "removeObserver(s) # Uninstalls the resident functionclassSelObserver:defsetPreselection(self,doc,obj,sub):# Preselection objectApp.Console.PrintMessage(str(sub)+"\n")# The part of the object namedefaddSelection(self,doc,obj,sub,pnt):# Selection objectApp.Console.PrintMessage("addSelection"+"\n")App.Console.PrintMessage(str(doc)+"\n")# Name of the documentApp.Console.PrintMessage(str(obj)+"\n")# Name of the objectApp.Console.PrintMessage(str(sub)+"\n")# The part of the object nameApp.Console.PrintMessage(str(pnt)+"\n")# Coordinates of the objectApp.Console.PrintMessage("______"+"\n")defremoveSelection(self,doc,obj,sub):# Delete the selected objectApp.Console.PrintMessage("removeSelection"+"\n")defsetSelection(self,doc):# Selection in ComboViewApp.Console.PrintMessage("setSelection"+"\n")defclearSelection(self,doc):# If click on the screen, clear the selectionApp.Console.PrintMessage("clearSelection"+"\n")# If click on another object, clear the previous objects=SelObserver()FreeCADGui.Selection.addObserver(s)# install the function mode resident#FreeCADGui.Selection.removeObserver(s) # Uninstall the resident function

Finding-selecting all elements below cursor

frompivyimportcoinimportFreeCADGuidefmouse_over_cb(event_callback):event=event_callback.getEvent()pos=event.getPosition().getValue()listObjects=FreeCADGui.ActiveDocument.ActiveView.getObjectsInfo((int(pos[0]),int(pos[1])))obj=[]iflistObjects:FreeCAD.Console.PrintMessage("\n *** Objects under mouse pointer ***")foroinlistObjects:label=str(o["Object"])ifnotlabelinobj:obj.append(label)FreeCAD.Console.PrintMessage("\n"+str(obj))view=FreeCADGui.ActiveDocument.ActiveViewmouse_over=view.addEventCallbackPivy(coin.SoLocation2Event.getClassTypeId(),mouse_over_cb)# to remove Callback :#view.removeEventCallbackPivy( coin.SoLocation2Event.getClassTypeId(), mouse_over)#####The easy way is probably to use FreeCAD's selection.#FreeCADGui.ActiveDocument.ActiveView.getObjectsInfo(mouse_coords)#####you get that kind of result :#'Document': 'Unnamed', 'Object': 'Box', 'Component': 'Face2', 'y': 8.604081153869629, 'x': 21.0, 'z': 8.553047180175781#####You can use this data to add your element to FreeCAD's selection :#FreeCADGui.Selection.addSelection(FreeCAD.ActiveDocument.Box,'Face2',21.0,8.604081153869629,8.553047180175781)

List the components of an object

# -*- coding: utf-8 -*-# This function list the components of an object# and extract this object its XYZ coordinates,# its edges and their lengths center of mass and coordinates# its faces and their center of mass# its faces and their surfaces and coordinates# 8/05/2014importDraft,Partdefdetail():sel=FreeCADGui.Selection.getSelection()# Select an objectiflen(sel)!=0:# If there is a selection thenVertx=[]Edges=[]Faces=[]compt_V=0compt_E=0compt_F=0pas=0perimetre=0.0EdgesLong=[]# Displays the "Name" and the "Label" of the selectionApp.Console.PrintMessage("Selection > "+str(sel[0].Name)+" "+str(sel[0].Label)+"\n"+"\n")forjinenumerate(sel[0].Shape.Edges):# Search the "Edges" and their lengthscompt_E+=1Edges.append("Edge%d"%(j[0]+1))EdgesLong.append(str(sel[0].Shape.Edges[compt_E-1].Length))perimetre+=(sel[0].Shape.Edges[compt_E-1].Length)# calculates the perimeter# Displays the "Edge" and its lengthApp.Console.PrintMessage("Edge"+str(compt_E)+" Length > "+str(sel[0].Shape.Edges[compt_E-1].Length)+"\n")# Displays the "Edge" and its center massApp.Console.PrintMessage("Edge"+str(compt_E)+" Center > "+str(sel[0].Shape.Edges[compt_E-1].CenterOfMass)+"\n")num=sel[0].Shape.Edges[compt_E-1].Vertexes[0]Vertx.append("X1: "+str(num.Point.x))Vertx.append("Y1: "+str(num.Point.y))Vertx.append("Z1: "+str(num.Point.z))# Displays the coordinates 1App.Console.PrintMessage("X1: "+str(num.Point[0])+" Y1: "+str(num.Point[1])+" Z1: "+str(num.Point[2])+"\n")try:num=sel[0].Shape.Edges[compt_E-1].Vertexes[1]Vertx.append("X2: "+str(num.Point.x))Vertx.append("Y2: "+str(num.Point.y))Vertx.append("Z2: "+str(num.Point.z))except:Vertx.append("-")Vertx.append("-")Vertx.append("-")# Displays the coordinates 2App.Console.PrintMessage("X2: "+str(num.Point[0])+" Y2: "+str(num.Point[1])+" Z2: "+str(num.Point[2])+"\n")App.Console.PrintMessage("\n")App.Console.PrintMessage("Perimeter of the form : "+str(perimetre)+"\n")App.Console.PrintMessage("\n")FacesSurf=[]forjinenumerate(sel[0].Shape.Faces):# Search the "Faces" and their surfacecompt_F+=1Faces.append("Face%d"%(j[0]+1))FacesSurf.append(str(sel[0].Shape.Faces[compt_F-1].Area))# Displays 'Face' and its surfaceApp.Console.PrintMessage("Face"+str(compt_F)+" > Surface "+str(sel[0].Shape.Faces[compt_F-1].Area)+"\n")# Displays 'Face' and its CenterOfMassApp.Console.PrintMessage("Face"+str(compt_F)+" > Center "+str(sel[0].Shape.Faces[compt_F-1].CenterOfMass)+"\n")# Displays 'Face' and its CoordinatesFacesCoor=[]fco=0forf0insel[0].Shape.Faces[compt_F-1].Vertexes:# Search the Vertexes of the facefco+=1FacesCoor.append("X"+str(fco)+": "+str(f0.Point.x))FacesCoor.append("Y"+str(fco)+": "+str(f0.Point.y))FacesCoor.append("Z"+str(fco)+": "+str(f0.Point.z))# Displays 'Face' and its CoordinatesApp.Console.PrintMessage("Face"+str(compt_F)+" > Coordinate"+str(FacesCoor)+"\n")# Displays 'Face' and its VolumeApp.Console.PrintMessage("Face"+str(compt_F)+" > Volume "+str(sel[0].Shape.Faces[compt_F-1].Volume)+"\n")App.Console.PrintMessage("\n")# Displays the total surface of the formApp.Console.PrintMessage("Surface of the form : "+str(sel[0].Shape.Area)+"\n")# Displays the total Volume of the formApp.Console.PrintMessage("Volume of the form : "+str(sel[0].Shape.Volume)+"\n")detail()

Cartesian coordinates

Change the value of "numberOfPoints" if you want a different number of points (precision)

numberOfPoints=100# Decomposition number (or precision you can change)selectedEdge=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0].copy()# select one elementpoints=selectedEdge.discretize(numberOfPoints)# discretize the elementi=0forpinpoints:# list and display the coordinatesi+=1printi," X",p.x," Y",p.y," Z",p.z

Other method display on "Int" and "Float"

importPartfromFreeCADimportBasec=Part.makeCylinder(2,10)# create the circlePart.show(c)# display the shape# slice accepts two arguments:#+ the normal of the cross section plane#+ the distance from the origin to the cross section plane. Here you have to find a value so that the plane intersects your objects=c.slice(Base.Vector(0,1,0),0)# # here the result is a single wire# depending on the source object this can be several wiress=s[0]# if you only need the vertexes of the shape you can usev=[]foriins.Vertexes:v.append(i.Point)# but you can also sub-sample the section to have a certain number of points (int) ...p1=s.discretize(20)ii=0foriinp1:ii+=1printi# Vector()printii,": X:",i.x," Y:",i.y," Z:",i.z# Vector decodeDraft.makeWire(p1,closed=False,face=False,support=None)# to see the difference accuracy (20)## uncomment to use#import Draft#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True) # first transform the DWire in Wire "downgrade"#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True) # second split the Wire in single objects "downgrade"###Draft.upgrade(FreeCADGui.Selection.getSelection(),delete=True) # to attach lines contiguous SELECTED use "upgrade"# ... or define a sampling distance (float)p2=s.discretize(0.5)ii=0foriinp2:ii+=1printi# Vector()printii,": X:",i.x," Y:",i.y," Z:",i.z# Vector decode Draft.makeWire(p2,closed=False,face=False,support=None)# to see the difference accuracy (0.5)## uncomment to use#import Draft#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True) # first transform the DWire in Wire "downgrade"#Draft.downgrade(App.ActiveDocument.ActiveObject,delete=True) # second split the Wire in single objects "downgrade"###Draft.upgrade(FreeCADGui.Selection.getSelection(),delete=True) # to attach lines contiguous SELECTED use "upgrade"

Find normal vector on the surface

This example show how to find normal vector on the surface by find the u,v parameters of one point on the surface and use u,v parameters to find normal vector

defnormal(self):ss=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[0].copy()#SubObjects[0] is the edge listpoints=ss.discretize(3.0)#points on the surface edge, #this example just use points on the edge for example. #However point is not necessary on the edge, it can be anywhere on the surface. face=FreeCADGui.Selection.getSelectionEx()[0].SubObjects[1]forppinpoints:pt=FreeCAD.Base.Vector(pp.x,pp.y,pp.z)#a point on the surface edgeuv=face.Surface.parameter(pt)# find the surface u,v parameter of a point on the surface edgeu=uv[0]v=uv[1]normal=face.normalAt(u,v)#use u,v to find normal vectorprintnormalline=Part.makeLine((pp.x,pp.y,pp.z),(normal.x,normal.y,normal.z))Part.show(line)