Python scripting tutorial: Difference between revisions

From FreeCAD Documentation
No edit summary
(Updated preferences location.)
 
(73 intermediate revisions by 9 users not shown)
Line 1: Line 1:
<languages/>
<languages/>
<translate>
<translate>
<!--T:59-->
{{docnav|Introduction to Python|FreeCAD Scripting Basics}}


<!--T:58-->
<!--T:59-->
{{Docnav
{{TutorialInfo
|[[Introduction_to_Python|Introduction to Python]]
|Topic=Programming
|[[FreeCAD_Scripting_Basics|FreeCAD Scripting Basics]]
|Level=Intermediate
|Time=
|Author=
|FCVersion=
|Files=
}}
}}


</translate>
{{TOCright}}
<translate>

==Introduction== <!--T:62-->


<!--T:1-->
<!--T:1-->
[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is a programming language, very simple to use and very fast to learn. It is open-source, multi-platform, and can be used alone for a wide array of things, from programming simple shell scripts to very complex programs. But one of its most widespread uses is as a scripting language, since it is easy to embed in other applications. That's exactly how it is used inside FreeCAD. From the python console, or from your custom scripts, you can pilot FreeCAD, and make it perform very complex actions for which there is still no graphical user interface tool.
[https://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is a programming language that it relatively easy to learn and understand. It is open-source and multi-platform, and can be used for many purposes: from 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|Python console]], or from custom scripts, you can control FreeCAD and make it perform very complex operations.


<!--T:2-->
<!--T:2-->
For example, from a python script, you can:
For example, from a Python script, you can:
* create new objects
* Create new objects.
* modify existing objects
* Modify existing objects.
* modify the 3D representation of those objects
* Modify the 3D representation of those objects.
* modify the FreeCAD interface
* Modify the FreeCAD interface.


<!--T:3-->
<!--T:3-->
There are also several different ways to use python in FreeCAD:
There are several ways to use Python in FreeCAD:
* From the [[FreeCAD Scripting Basics|FreeCAD python interpreter]], where you can issue simple commands like in a "command line"-style interface
* From the [[FreeCAD Scripting Basics|FreeCAD Python interpreter]], where you can issue commands in a "command line"-style interface.
* From [[macros|macros]], which are a convenient way to quickly add a missing tool to the FreeCAD interface
* From [[macros|macros]], which are a convenient way to quickly add a missing tool to the FreeCAD interface.
* From external scripts, which can be used to program much more complex things. like entire [[Workbenches|Workbenches]].
* From external scripts, which can used to create quite complex solutions, even entire [[Workbenches|Workbenches]].


<!--T:4-->
<!--T:4-->
In this tutorial, we'll work on a couple of simple examples to get you started, but there is also much more [[Power users hub|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|introduction to Python]].
In this tutorial, we'll work on a couple of basic examples to get you started, but there is much more [[Power users hub|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|introduction to Python]].


<!--T:5-->
<!--T:5-->
'''Important!''' Before proceeding with Python scripting, go to {{MenuCommand|Edit → Prefences → General → Output}} window and check 2 boxes:
Before proceeding with Python scripting, go to {{MenuCommand|Edit → Preferences → General → Report view}} and check two boxes:
* Redirect internal Python output to report view
* {{MenuCommand|Redirect internal Python output to report view}}.
* Redirect internal Python errors to report view
* {{MenuCommand|Redirect internal Python errors to report view}}.
Then go to {{MenuCommand|View → Panels}} and check:
Then go to {{MenuCommand|View → Panels}} and check:
* Report view
* {{MenuCommand|Report view}}.
This will save you a lot of aggravation!


== Writing python code == <!--T:6-->
==Writing Python code== <!--T:6-->
There are two easy ways to write python code in FreeCAD: From the python console (available from the View → Panels → Python console menu) or from the Macro editor (Tools → Macros). In the console, you write python commands one by one, which are executed when you press return, while the macros can contain a more complex script made of several lines, which is executed only when the macro is executed.


<!--T:63-->
There are two ways to write Python code in FreeCAD. In the [[Python console|Python console]] (select {{MenuCommand|View → Panels → Python console}} from the menu) or in the [[Std_DlgMacroExecute|Macro editor]] (select {{MenuCommand|Macro → Macros...}} from the menu). In the console you write Python commands one by one, executing them by pressing {{KEY|Enter}}, while macros can contain more complex code made up of several lines, executed only when the macro is executed.

</translate>
[[Image:Screenshot_pythoninterpreter.jpg]]
<translate>
<!--T:7-->
<!--T:7-->
[[Image:Screenshot_pythoninterpreter.jpg|center|frame|The FreeCAD python console]]
{{Caption|The FreeCAD Python console}}


<!--T:8-->
<!--T:8-->
In this tutorial, you will be able to use both methods, either by copying/pasting each line one by one in the python console and pressing {{KEY|Return}} after each line, or by copying/pasting the entire code in a new Macro window.
In this tutorial you can use both methods. You can copy-paste each line in the Python console and then press {{KEY|Enter}}, or copy-paste the entire code in a new Macro window.


</translate>{{Top}}<translate>
== Exploring FreeCAD == <!--T:9-->

==Exploring FreeCAD== <!--T:9-->

<!--T:64-->
Let's start by creating a new empty document:
Let's start by creating a new empty document:


Line 61: Line 68:


<!--T:10-->
<!--T:10-->
If you type this in the FreeCAD python console, you will notice that as soon as you type "FreeCAD.", a windows 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 very easy to explore the functionality available. Before choosing "newDocument", have a look at the other options available.
If you type this in the FreeCAD Python console, you will notice that as soon as you type {{incode|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 {{incode|newDocument}}, have a look at the other options.


</translate>
[[Image:Screenshot_classbrowser.jpg]]
<translate>
<!--T:11-->
<!--T:11-->
[[Image:Screenshot_classbrowser.jpg|center|frame|The autocomplete mechanism of the FreeCAD python console]]
{{Caption|The autocomplete mechanism of the FreeCAD Python console}}


<!--T:12-->
<!--T:12-->
Now our new document will be created. This is similar to pressing the "new document" button on the toolbar. In fact, most buttons in FreeCAD do nothing else than executing a line or two of python code. Even better, you can set an option in {{MenuCommand|Edit → Preferences → General → Macro}} to "show script commands in python console". This will print in the console all python code executed when you press buttons. Very useful to learn how to reproduce actions in python.
Now our new document will be created. This is similar to pressing the {{Button|[[Image:Std_New.svg|16px]] [[Std_New|New]]}} 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 {{MenuCommand|Edit → Preferences → Python → Macro}} to {{MenuCommand|Show script commands in python console}}. This will print in the console all Python code executed when you press buttons. Very useful for learning how to reproduce actions in Python.


<!--T:13-->
<!--T:13-->
Now let's get back to our document. Let's see what we can do with it:
Now let's get back to our document and see what we can do with it:


</translate>
</translate>
Line 79: Line 89:


<!--T:14-->
<!--T:14-->
Explore the available options. Usually names that begin with a capital letter are attributes, they contain a value, while names that begin with small 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:
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:


</translate>
</translate>
{{Code|code=
{{Code|code=
box = doc.addObject("Part::Box","myBox")
box = doc.addObject("Part::Box", "myBox")
}}
}}
<translate>
<translate>


<!--T:15-->
<!--T:15-->
Nothing happens. Why? Because FreeCAD is made for the big picture. One day, it will work with hundreds of complex objects, all depending one from another. 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:
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:


</translate>
</translate>
Line 97: Line 107:


<!--T:16-->
<!--T:16-->
See? Now our box appeared! Many of the buttons that add objects in FreeCAD actually do 2 things: add the object, and recompute. If you turned on the "show script commands in python console" option above, try now adding a sphere with the GUI button, you'll see the two lines of python code being executed one after the other.
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 {{MenuCommand|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.

<!--T:17-->
What about the "Part::Box" will you ask? How can I know what other kind of objects can be added? It's all here:

</translate>
{{Code|code=
doc.supportedTypes()
}}
<translate>


<!--T:18-->
<!--T:18-->
Line 136: Line 137:


<!--T:21-->
<!--T:21-->
If you select your box with the mouse, you'll see that in the properties panel, in the "Data" tab, our "Height" property appears. All properties of a FreeCAD object that appear there (and also in the "View" tab, more about that later), are directly accessible by python too, by their names, like we did with the "Height" property. Try changing the other dimensions of that box.
If you select your box with the mouse, you'll see that in the [[Property_editor|Property editor]], on the {{MenuCommand|Data}} tab, our {{PropertyData|Height}} property appears. All properties of a FreeCAD object that appear there (and also on the {{MenuCommand|View}} tab, more about that later), are directly accessible in Python too, by their names, like we did with the {{PropertyData|Height}} property. Try changing the other dimensions of the box.


</translate>{{Top}}<translate>
== Vectors and Placements == <!--T:22-->

[http://en.wikipedia.org/wiki/Euclidean_vector Vectors] are a very fundamental concept in any 3D application. It is a list of 3 numbers (x, y and z), describing a point or position in the 3D space. A lot of things can be done with vectors, such as additions, subtractions, projections and [http://en.wikipedia.org/wiki/Vector_space much more]. In FreeCAD vectors work like this:
==Vectors and placements== <!--T:22-->

<!--T:73-->
[https://en.wikipedia.org/wiki/Euclidean_vector Vectors] are a very fundamental concept in any 3D application. A vector is a list of 3 numbers (x, y and z), describing a point or position in 3D space. Many things can be done with vectors, such as additions, subtractions, projections and [https://en.wikipedia.org/wiki/Vector_space much more]. In FreeCAD vectors work like this:


</translate>
</translate>
{{Code|code=
{{Code|code=
myvec = FreeCAD.Vector(2,0,0)
myvec = FreeCAD.Vector(2, 0, 0)
myvec
myvec.x
myvec.x
myvec.y
myvec.y
othervec = FreeCAD.Vector(0,3,0)
othervec = FreeCAD.Vector(0, 3, 0)
sumvec = myvec.add(othervec)
sumvec = myvec.add(othervec)
}}
}}
Line 153: Line 157:


<!--T:23-->
<!--T:23-->
Another common feature of FreeCAD objects is their [[Placement|placement]]. Each object has a Placement attributes, which contains the position (Base) and orientation (Rotation) of the object. It is easy to manipulate, for example to move our object:
Another common feature of FreeCAD objects is their [[Placement|placement]]. Each object has a {{PropertyData|Placement}} property, which contains the {{PropertyData|Base}} (position) and {{PropertyData|Rotation}} (orientation) of the object. It is easy to manipulate, for example to move our object:


</translate>
</translate>
Line 169: Line 173:
Now you must understand a couple of important concepts before we get further.
Now you must understand a couple of important concepts before we get further.


</translate>{{Top}}<translate>
== App and Gui == <!--T:25-->

FreeCAD is made from the beginning to work as a command-line application, without its user interface. As a result, almost everything is separated between a "geometry" component and a "visual" component. When you work in command-line mode, the geometry part is present, but all the visual part is simply disabled. Almost any object in FreeCAD therefore is made of two parts, an Object and a ViewObject.
==App and Gui== <!--T:25-->

<!--T:65-->
FreeCAD has been designed so that it can also be used without its user interface, as a command-line application. Almost every object in FreeCAD therefore consists of two parts: an {{incode|Object}}, its "geometry" component, and a {{incode|ViewObject}}, its "visual" component. When you work in command-line mode, the geometry part is present, but the visual part is disabled.


<!--T:26-->
<!--T:26-->
To illustrate the concept, see 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 window. The view object of an object is accessed like this:
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 {{incode|Object}}. While its visual properties, such as its color, line thickness, etc. are stored in the {{incode|ViewObject}}. This corresponds to the '''Data''' and '''View''' tabs in the [[Property_editor|Property editor]]. The view object of an object is accessed like this:


</translate>
</translate>
Line 181: Line 189:
<translate>
<translate>
<!--T:27-->
<!--T:27-->
Now you can also change the properties of the "View" tab:
Now you can also change the properties on the '''View''' tab:


</translate>
</translate>
Line 192: Line 200:


<!--T:28-->
<!--T:28-->
When you start FreeCAD, the python console already loads 2 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. 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
When you start FreeCAD, the Python console already loads two base modules: {{incode|FreeCAD}} and {{incode|FreeCADGui}} (which can also be accessed by their shortcuts {{incode|App}} and {{incode|Gui}}). They contain all kinds of generic functionality to work with documents and their objects. To illustrate our concept, see that both {{incode|FreeCAD}} and {{incode|FreeCADGui}} contain an {{incode|ActiveDocument}} attribute, which is the currently opened document. {{incode|FreeCAD.ActiveDocument}} and {{incode|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, {{incode|FreeCADGui.ActiveDocument}} contains {{incode|ActiveView}}, which is the currently opened [[3D_view|3D view]].


</translate>{{Top}}<translate>
== Modules == <!--T:29-->

Now, you must be wondering, what, other than "Part::Box", can I do? The FreeCAD base application is more or less an empty container. Without its modules, it can do little more than create new, empty documents. The true power of FreeCAD is in its faithful modules. Each of them adds not only new workbenches to the interface, but also new python commands and new object types. As a result, several different or even totally incompatible object types can coexist in the same document. The most important modules in FreeCAD, that we'll look at in this tutorial, are [[Part Module|Part]], [[Mesh Module|Mesh]], [[Sketcher Workbench|Sketcher]] and [[Draft Module|Draft]].
==Modules== <!--T:29-->

<!--T:66-->
The true power of FreeCAD lies in its faithful modules, with their respective workbenches. The FreeCAD base application is more or less an empty container. Without its modules it can do little more than create new, empty documents. Each module not only adds new workbenches to the interface, but also new Python commands and new object types. As a result several different, and even totally incompatible, object types can coexist in the same document. The most important modules in FreeCAD that we'll look at in this tutorial are: [[Part_Workbench|Part]], [[Mesh_Workbench|Mesh]], [[Sketcher_Workbench|Sketcher]] and [[Draft_Workbench|Draft]].


<!--T:30-->
<!--T:30-->
[[Sketcher Workbench|Sketcher]] and [[Draft Module|Draft]] both use the [[Part Module|Part]] module to create and handle their geometry, which are BRep while [[Mesh Module|Mesh]] is totally independent, and handles its own objects. More about that below.
[[Sketcher_Workbench|Sketcher]] and [[Draft_Workbench|Draft]] both use the [[Part_Workbench|Part]] module to create and handle their geometry. While [[Mesh_Workbench|Mesh]] is totally independent, and handles its own objects. More about that below.


<!--T:31-->
<!--T:31-->
Line 210: Line 222:


<!--T:32-->
<!--T:32-->
The different FreeCAD modules, although they added their object types to FreeCAD, 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:
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:


</translate>
</translate>
Line 222: Line 234:
But we'll talk more about the Part module below.
But we'll talk more about the Part module below.


</translate>{{Top}}<translate>
<!--T:34-->
By now, you know a bit more about the different modules of FreeCAD: The core modules (FreeCAD, FreeCADGui), and the workbench modules (Part, Mesh, Sketcher). The other important modules are the 3d scene module (pivy) and the interface module (pyside), we'll talk about them too below.


<!--T:35-->
==Mesh module== <!--T:36-->
Now it's time to explore a bit deeper the important ones, which are the workbench modules.

== Mesh == <!--T:36-->


<!--T:37-->
<!--T:37-->
[http://en.wikipedia.org/wiki/Polygon_mesh Meshes] are a very simple kind of 3D object, used for example by [http://en.wikipedia.org/wiki/SketchUp Sketchup], [http://en.wikipedia.org/wiki/Blender_%28software%29 Blender] or [http://en.wikipedia.org/wiki/Autodesk_3ds_Max 3D studio Max]. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. Of course, nothing prevents you from having a bigger plane face made of several coplanar triangles.
[https://en.wikipedia.org/wiki/Polygon_mesh Meshes] are a very simple kind of 3D object, used for example by [https://en.wikipedia.org/wiki/SketchUp Sketchup], [https://en.wikipedia.org/wiki/Blender_(software) Blender] and [https://en.wikipedia.org/wiki/Autodesk_3ds_Max 3D Studio Max]. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. Of course, nothing prevents you from having a bigger face made up of several coplanar triangles.


<!--T:38-->
<!--T:38-->
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 (.stl, .obj) from other applications. The Mesh module was also used extensively as the main test module in the first month of FreeCAD's life.
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 ({{FileName|.stl}}, {{FileName|.obj}}) from other applications. The Mesh module was also used extensively as the main test module in the first month of FreeCAD's life.


<!--T:39-->
<!--T:39-->
Line 243: Line 251:
import Mesh
import Mesh
mymesh = Mesh.createSphere()
mymesh = Mesh.createSphere()
mymesh.
mymesh.Facets
mymesh.Facets
mymesh.Points
mymesh.Points
meshobj = doc.addObject("Mesh::Feature","MyMesh")
meshobj = doc.addObject("Mesh::Feature", "MyMesh")
meshobj.Mesh = mymesh
meshobj.Mesh = mymesh
doc.recompute()
doc.recompute()
Line 254: Line 261:


<!--T:40-->
<!--T:40-->
This is a standard example that uses the createSphere() method to automatically create a sphere, but you can also create custom meshes from scratch by defining their vertices and faces.
This is a standard example that uses the {{incode|createSphere()}} method to create a sphere, but you can also create custom meshes from scratch by defining their vertices and faces.


<!--T:41-->
<!--T:41-->
[[Mesh Scripting|Read more about mesh scripting...]]
[[Mesh Scripting|Read more about mesh scripting...]]


</translate>{{Top}}<translate>
== Part == <!--T:42-->

The [[Part Module|Part Module]] is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate [http://en.wikipedia.org/wiki/Boundary_representation BRep] objects. This kind of object, unlike meshes, can have a wide variety of components. Brep stands for Boundary Representation, which means that Brep objects are defined by their surfaces; those surfaces enclose and define an inner volume. A surface can be a variety of things such as plane faces or very complex NURBS surfaces.
==Part module== <!--T:42-->

<!--T:67-->
The [[Part_Workbench|Part]] module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate [https://en.wikipedia.org/wiki/Boundary_representation BRep] objects. BREP stands for "Boundary Representation". A BREP object is defined by surfaces that enclose and define an inner volume. Unlike meshes, BREP objects can have a wide variety of components from planar faces to very complex NURBS surfaces.


<!--T:43-->
<!--T:43-->
The Part module is based on the powerful [http://en.wikipedia.org/wiki/Open_CASCADE_Technology OpenCasCade] library, which allows a wide range of complex operations to be easily performed on those objects, such as boolean operations, filleting, lofts, etc...
The Part module is based on the powerful [https://en.wikipedia.org/wiki/Open_CASCADE_Technology OpenCasCade] library, which allows a wide range of complex operations to be performed on those objects, such as boolean operations, filleting, lofts, etc.


<!--T:44-->
<!--T:44-->
Line 272: Line 283:
import Part
import Part
myshape = Part.makeSphere(10)
myshape = Part.makeSphere(10)
myshape.
myshape.Volume
myshape.Volume
myshape.Area
myshape.Area


shapeobj = doc.addObject("Part::Feature","MyShape")
shapeobj = doc.addObject("Part::Feature", "MyShape")
shapeobj.Shape = myshape
shapeobj.Shape = myshape
doc.recompute()
doc.recompute()
Line 283: Line 293:


<!--T:45-->
<!--T:45-->
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 above to:
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:


</translate>
</translate>
Line 292: Line 302:


<!--T:46-->
<!--T:46-->
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|Topological data scripting]] page explains all that in detail.
By exploring the contents of myshape, you will notice many interesting subcomponents such as {{incode|Faces}}, {{incode|Edges}}, {{incode|Vertexes}}, {{incode|Solids}} and {{incode|Shells}}, and a wide range of geometry operations such as {{incode|cut}} (subtraction), {{incode|common}} (intersection) or {{incode|fuse}} (union). The [[Topological_data_scripting|Topological data scripting]] page explains all that in detail.


<!--T:47-->
<!--T:47-->
[[Topological data scripting|Read more about part scripting...]]
[[Topological_data_scripting|Read more about part scripting...]]


</translate>{{Top}}<translate>
== Draft == <!--T:48-->

FreeCAD features many more modules, such as [[Sketcher Workbench|Sketcher]] and [[Draft Module|Draft]], which also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to [[Scripted objects|create such objects in python]].
==Draft module== <!--T:48-->

<!--T:68-->
FreeCAD features many more modules, such as [[Sketcher_Workbench|Sketcher]] and [[Draft_Workbench|Draft]], that also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to [[Scripted_objects|create such objects in Python]].


<!--T:49-->
<!--T:49-->
The [[Draft Module|Draft Module]] adds 2D parametric object types (which are all Part objects) such as lines and circles, and also provides some generic functions that work not only on Draft-made objects, but on any Part object. To explore what is available, simply do:
The [[Draft_Workbench|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:


</translate>
</translate>
{{Code|code=
{{Code|code=
import Draft
import Draft
rec = Draft.makeRectangle(5, 2)
Draft.
mvec = FreeCAD.Vector(4, 4, 0)
rec = Draft.makeRectangle(5,2)
Draft.move(rec, mvec)
mvec = FreeCAD.Vector(4,4,0)
Draft.move(rec,mvec)
Draft.move(box, mvec)
Draft.move(box,mvec)
}}
}}
<translate>
<translate>


</translate>{{Top}}<translate>
== Interface == <!--T:50-->

The FreeCAD user interface is made with [http://en.wikipedia.org/wiki/Qt_%28framework%29 Qt], 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. Let's try to fiddle with the Qt interface and produce a simple dialog:
==Interface== <!--T:50-->

<!--T:69-->
The FreeCAD user interface is made with [https://en.wikipedia.org/wiki/Qt_(software) Qt], a powerful graphical interface system, responsible for drawing and handling all the controls, menus, toolbars and buttons around the [[3D_view|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:


</translate>
</translate>
{{Code|code=
{{Code|code=
from PySide import QtGui
from PySide import QtGui
QtGui.QMessageBox.information(None,"Apollo program","Houston, we have a problem")
QtGui.QMessageBox.information(None, "Apollo program", "Houston, we have a problem")
}}
}}
<translate>
<translate>


<!--T:51-->
<!--T:51-->
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. We can therefore easily directly manipulate any part of the FreeCAD interface.
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.


<!--T:52-->
<!--T:52-->
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.
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.


<!--T:53-->
<!--T:53-->
[[PySide|Read more about PySide here...]]
[[PySide|Read more about PySide here...]]


</translate>{{Top}}<translate>
== Macros == <!--T:54-->

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 easily from FreeCAD? There is an easy mechanism for that, called [[Macros|Macros]]. A macro is simply 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 → Customiz → Macros to define a button for it that can be added to toolbars.
==Macros== <!--T:54-->

<!--T:70-->
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|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 ({{MenuCommand|Macro → Macros... → Create}}) where you can write or paste scripts. Once the script is done, use {{MenuCommand|Tools → Customize... → Macros}} to define a button for it that can be added to toolbars.

==External scripts== <!--T:82-->

<!--T:83-->
An alternative method for creating, saving, and running your own Python scripts is to create them outside FreeCAD, using an editor of your choice (for example, Vim). To run your Python script inside FreeCAD, be sure to save it with the {{FileName|.py}} extension.

<!--T:84-->
Then use {{MenuCommand|File → Open}} to open your script. It will load into a new tab in the [[Main_view_area|Main view area]]. You can run your script by clicking the {{Button|[[Image:Std_DlgMacroExecuteDirect.svg|16px]] [[Std_DlgMacroExecuteDirect|Execute macro]]}} button. Any errors or script output will be shown in the [[Report_view|Report view]].

<!--T:85-->
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.


<!--T:55-->
<!--T:55-->
You can continue to the [[FreeCAD_Scripting_Basics|FreeCAD Scripting Basics]] page, or you can access that page and other relevant pages at the [[Power_users_hub|Power users hub]].
Now you are ready for more in-depth FreeCAD scripting. Head on to the [[Power users hub|Power users hub]]!

</translate>{{Top}}<translate>



<!--T:56-->
<!--T:56-->
{{Docnav
{{docnav|Introduction to Python|FreeCAD Scripting Basics}}
|[[Introduction_to_Python|Introduction to Python]]
|[[FreeCAD_Scripting_Basics|FreeCAD Scripting Basics]]
}}


</translate>
</translate>
{{Userdocnavi{{#translation:}}}}
{{Powerdocnavi{{#translation:}}}}
[[Category:Poweruser Documentation{{#translation:}}]]
[[Category:Developer Documentation{{#translation:}}]]
[[Category:Python Code{{#translation:}}]]
{{clear}}

Latest revision as of 20:17, 9 August 2023

Introduction

Python is a programming language that it relatively easy to learn and understand. It is open-source and multi-platform, and can be used for many purposes: from 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.

For example, from a Python script, you can:

  • Create new objects.
  • Modify existing objects.
  • Modify the 3D representation of those objects.
  • Modify the FreeCAD interface.

There are several ways to use Python in FreeCAD:

  • From the FreeCAD Python interpreter, where you can issue commands in a "command line"-style interface.
  • 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:

  • Redirect internal Python output to report view.
  • Redirect internal Python errors to report view.

Then go to View → Panels and check:

  • Report view.

Writing Python code

There are two ways to write Python code in FreeCAD. In the Python console (select View → Panels → Python console from the menu) or in the Macro editor (select Macro → Macros... from the menu). In the console you write Python commands one by one, executing them by pressing Enter, while macros can contain more complex code made up of several lines, executed only when the macro is executed.

The FreeCAD Python console

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

Exploring FreeCAD

Let's start by creating a new empty document:

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.

The autocomplete mechanism of the FreeCAD Python console

Now our new document will be created. This is similar to pressing the New 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 learning 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:

box = doc.addObject("Part::Box", "myBox")

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.

Now let's explore the contents of our box:

box.

You'll immediately see a couple of very interesting things such as:

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 DataHeight 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 DataHeight property. Try changing the other dimensions of the box.

Top

Vectors and placements

Vectors are a very fundamental concept in any 3D application. A vector is a list of 3 numbers (x, y and z), describing a point or position in 3D space. Many things can be done with vectors, such as additions, subtractions, projections and much more. In FreeCAD vectors work like this:

myvec = FreeCAD.Vector(2, 0, 0)
myvec.x
myvec.y
othervec = FreeCAD.Vector(0, 3, 0)
sumvec = myvec.add(othervec)

Another common feature of FreeCAD objects is their placement. Each object has a DataPlacement property, which contains the DataBase (position) and DataRotation (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

App and Gui

FreeCAD has been designed so that it can also be used without its user interface, as a command-line application. Almost every object in FreeCAD therefore consists of two parts: an Object, its "geometry" component, and a ViewObject, its "visual" component. When you work in command-line mode, the geometry part is present, but the visual part is disabled.

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 you can also change 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

Modules

The true power of FreeCAD lies in its faithful modules, with their respective workbenches. The FreeCAD base application is more or less an empty container. Without its modules it can do little more than create new, empty documents. Each module not only adds new workbenches to the interface, but also new Python commands and new object types. As a result several different, and even totally incompatible, object types can coexist in the same document. The most important modules in FreeCAD that we'll look at in this tutorial are: Part, Mesh, Sketcher and Draft.

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.

But we'll talk more about the Part module below.

Top

Mesh module

Meshes are a very simple kind of 3D object, used for example by Sketchup, Blender and 3D Studio Max. They are composed of 3 elements: points (also called vertices), lines (also called edges) and faces. In many applications, FreeCAD included, faces can have only 3 vertices. Of course, nothing prevents you from having a bigger face made up of several coplanar triangles.

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 (.stl, .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
 
meshobj = doc.addObject("Mesh::Feature", "MyMesh")
meshobj.Mesh = mymesh
doc.recompute()

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.

Read more about mesh scripting...

Top

Part module

The Part module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate BRep objects. BREP stands for "Boundary Representation". A BREP object is defined by surfaces that enclose and define an inner volume. Unlike meshes, BREP objects can have a wide variety of components from planar faces to very complex NURBS surfaces.

The Part module is based on the powerful OpenCasCade 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

shapeobj = doc.addObject("Part::Feature", "MyShape")
shapeobj.Shape = myshape
doc.recompute()

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.

Read more about part scripting...

Top

Draft module

FreeCAD features many more modules, such as Sketcher and Draft, that also create Part objects. These modules add additional parameters to the objects created, or even implement a whole new way to handle the Part geometry in them. Our box example above is a perfect example of a parametric object. All you need to define the box is to specify the parameters height, width and length. Based on those, the object will automatically calculate its Part shape. FreeCAD allows you to create such objects in Python.

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)
Draft.move(rec, mvec)
Draft.move(box, mvec)

Top

Interface

The FreeCAD user interface is made with Qt, 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:

from PySide import QtGui
QtGui.QMessageBox.information(None, "Apollo program", "Houston, we have a problem")

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.

Read more about PySide here...

Top

Macros

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.

External scripts

An alternative method for creating, saving, and running your own Python scripts is to create them outside FreeCAD, using an editor of your choice (for example, Vim). To run your Python script inside FreeCAD, be sure to save it with the .py extension.

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 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