Python scripting tutorial FreeCAD Documentation (1)
Python scripting tutorial FreeCAD Documentation (1)
This is the approved revision of this page, as well as being the most recent.
Beginning
Introduction Other languages: Bahasa Indonesia® Deutsch® English® Turkge™ espafiol® francais® italiano® polski® portugués ™ portugués do Brasil
Writing Python code romana® &edtina® pycckmitd I3 (PEAPEE) HAZE « =0
Mesh module simple shell scripts to very complex programs. But its most widespread use is as a scripting language embedded in other applications. That is how it is used inside
FreeCAD. From the Python console, or from custom scripts, you can control FreeCAD and make it perform very complex operations.
Part module
For example, from a Python script, you can:
Draft module
« Create new objects.
Interface
s Modify existing objects.
Macros e lodify the 3D representation of those objects.
External scripts + Modify the FreeCAD interface.
* From the FreeCAD Python interpreter, where you can issue commands in a "command line"-style interface.
s From macros, which are a convenient way to quickly add a missing tool to the FreeCAD interface.
» From external scripts, which can used to create quite complex solutions, even entire Workbenches.
In this tutorial, we'll work on a couple of basic examples to get you started, but there is much more documentation about Python scripting available on this wiki. If
you are totally new to Python and want to understand how it works, we also have a basic introduction to Python.
Before proceeding with Python scripting, go to Edit — Preferences — General — Report view and check two boxes:
* Report view.
In this tutorial you can use both methods. You can copy-paste each line in the Python console and then press | Enter |, or copy-paste the entire code in a new
Macro window.
Top
doc = FreeCAD.newDocument()
If you type this in the FreeCAD Python console, you will notice that as soon as you type FreeCAD. a window pops up, allowing to quickly autocomplete the rest of
your line. Even better, each entry in the autocomplete list has a tooltip explaining what it does. This makes it easier to explore the available functionality. Before
choosing newDocument | have a look at the other options.
Report view 9
Python | =@ SendMsgToActiveView [a|B. 03:56:44)
[cece 4, @ doc_ activeDocument() -> object or None
Type 'h| @ __name__ |
>>> GL ¢ activateWorkbench {Return the active document or None if no one exists
el B, cctiveDocument )
>>> Ar ¢ actlveWorkbench Jment(“Unnamed"”)
S5 GL @ addCammand Thent("Unnamed”)
>>> Gll,
Now our new document will be created. This is similar to pressing the button on the toolbar. In fact most buttons in FreeCAD do nothing more than
execute one or more lines of Python code. Even better, you can set an option in Edit — Preferences — Python — Macro to Show script commands in python
console. This will print in the console all Python code executed when you press buttons. Very useful for learing how to reproduce actions in Python.
Now let's get back to our document and see what we can do with it:
doc.
Explore the available options. Usually names that begin with a capital letter are attributes, they contain a value, while names that begin with a lower case letter are
functions (also called methods), they "do something". Names that begin with an underscore are usually there for the internal working of the module, and you
shouldn't care about them. Let's use one of the methods to add a new object to our document:
Nothing happens. Why? Because FreeCAD is made for the big picture. One day, it will work with hundreds of complex objects, all depending each other. Making a
small change somewhere could have a big impact; you may need to recalculate the whole document which could take a long time. For that reason almost no
command updates the scene automatically. You must do it manually:
doc . recompute()
Now our box appeared. Many of the buttons that add objects in FreeCAD actually do two things: add the object, and recompute. If you turned on the Show script
commands in python console option above, try adding a sphere with the GUI button; you'll see the two lines of Python code being executed one after the other.
box.
box.Height
This will print the current height of our box. Now let's try to change that:
box.Height = 5
If you select your box with the mouse, you'll see that in the Property editor, on the Data tab, our o= Height property appears. All properties of a FreeCAD object
that appear there (and also on the View tab, more about that later), are directly accessible in Python too, by their names, like we did with the o= Height property.
Try changing the other dimensions of the box.
Top
myvec = FreeCAD.Vector(2, 0, @)
myvec.x
myvec.y
othervec = FreeCAD.Vector(0, 2, @)
sumvec = myvec.add(othervec)
Another common feature of FreeCAD objects is their placement. Each object has a oaa Placement property, which contains the oaa Base (position) and
paa Rotation (orientation) of the object. It is easy to manipulate, for example to move our object:
box.Placement
box.Placement.Base
box.Placement.Base = sumvec
otherpla = FreeCAD.Placement()
box.Placement = otherpla
Now you must understand a couple of important concepts before we get further.
Top
To illustrate the concept let's look at our cube object. The geometric properties of the cube, such as its dimensions, position, etc. are stored in the Object . While
its visual properties, such as its color, line thickness, etc. are stored in the ViewObject . This corresponds to the Data and View tabs in the Property editor. The
view object of an object is accessed like this:
vo = box.ViewObject
Now vou can also chanae the properties on the View tab:
vo.Transparency = 80
vo.hide()
vo.show()
When you start FreeCAD, the Python console already loads two base modules: FreeCAD and FreeCADGui (which can also be accessed by their shortcuts App
and Gui ). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both FreeCAD and
FreeCADGui contain an ActiveDocument attribute, which is the currently opened document. FreeCAD.ActiveDocument and FreeCADGui.ActiveDocument
are not the same object however. They are the two components of a FreeCAD document, and they contain different attributes and methods. For example,
FreeCADGui.ActiveDocument contains ActiveView , which is the currently opened 3D view.
Top
Sketcher and Draft both use the Part module to create and handle their geometry. While Mesh is totally independent, and handles its own objects. More about that
below.
You can check all the available base object types for the current document like this:
doc. supportedTypes()
The different FreeCAD modules are not automatically loaded in the Python console. This is to avoid having a very slow startup. Modules are loaded only when you
need them. So, for example, to explore what's inside the Part module:
import Part
Part.
Top
Meshes are simple, but because they are simple you can easily have millions of them in a single document. However, in FreeCAD they have less use and are
mostly there so you can import objects in mesh formats (.st1, .obj) from other applications. The Mesh module was also used extensively as the main test module
in the first month of FreeCAD's life.
Mesh objects and FreeCAD objects are different things. You can see the FreeCAD object as a container for a Mesh object (and as we'll see below, for Part objects
also). So in order to add a mesh object to FreeCAD, we must first create a FreeCAD object and a Mesh object, then add the Mesh object to the FreeCAD object:
import Mesh
mymesh = Mesh.createSphere()
mymesh.Facets
mymesh.Points
This is a standard example that uses the createSphere() method to create a sphere, but you can also create custom meshes from scratch by defining their
vertices and faces.
Top
The Part module is based on the powerful OpenCasCade 7 library, which allows a wide range of complex operations to be performed on those objects, such as
boolean operations, filleting, lofts, etc.
The Part module works the same way as the Mesh module: You create a FreeCAD object, a Part object, then add the Part object to the FreeCAD object:
import Part
myshape = Part.makeSphere(10)
myshape .Volume
myshape.Area
The Part module (like the Mesh module) also has a shortcut that automatically creates a FreeCAD object and adds a shape to it, so you can shorten the last three
lines to:
Part.show(myshape)
By exploring the contents of myshape, you will notice many interesting subcomponents such as Faces , Edges , Vertexes , Solids and Shells , and a wide
range of geometry operations such as cut (subtraction), common (intersection) or fuse (union). The Topological data scripting page explains all that in detail.
Top
The Draft module adds 2D parametric object types (which are all Part objects) such as lines and circles, and also provides some generic functions that not only
work on Draft objects, but on any Part object. To explore what is available, simply do:
import Draft
rec = Draft.makeRectangle(5, 2)
mvec = FreeCAD.Vector(4, 4, 0)
Nraft move(rer, muer)
Draft.move(box, mvec)
Top
The FreeCAD user interface is made with Qtr7, a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars and
buttons around the 3D view. Qt provides a module, PySide, which allows Python to access and modify Qt interfaces such as FreeCAD's. Let's try to fiddle with the
Qt interface and produce a simple dialog:
Notice that the dialog that appears has the FreeCAD icon in its toolbar, meaning that Qt knows that the order has been issued from inside the FreeCAD application.
It is possible to manipulate any part of the FreeCAD interface.
Qt is a very powerful interface system that allows you to do very complex things. It also has some easy-to-use tools such as the Qt Designer with which you can
design dialogs graphically and then add them to the FreeCAD interface with a few lines of Python code.
Top
Now that you have a good understanding of the basics, where are we going to keep our Python scripts, and how are we going to launch them inside FreeCAD?
There is an easy mechanism for that, called Macros. A macro is a Python script that can be added to a toolbar and launched via a mouse click. FreeCAD provides
you with a simple text editor (Macro — Macros... — Create) where you can write or paste scripts. Once the script is done, use Tools — Customize... — Macros
to define a button for it that can be added to toolbars.
Then use File — Open to open your script, It will load into a new tab in the Main view area. You can run your script by clicking the [ b- Execute macro ] button.
Any errors or script output will be shown in the Report view.
When you make and save any modifications to your already-loaded script, a dialog box will appear asking whether you want to reload the modified script into
FreeCAD.
You can continue to the FreeCAD Scripting Basics page, or you can access that page and other relevant pages at the Power users hub.
Top
Debug data: