Manual:A gentle introduction: Difference between revisions

From FreeCAD Documentation
(Created page with "<translate> {{Manual:TOC}} [https://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is a widely popular, open-source programming language, very often used as...")
 
m (Arrows exchanged)
 
(20 intermediate revisions by 10 users not shown)
Line 1: Line 1:
<languages/>
<translate>
<translate>

<!--T:45-->
{{Docnav
|[[Manual:Creating_renderings|Creating renderings]]
|[[Manual:Creating_and_manipulating_geometry|Creating and manipulating geometry]]
|[[Manual:Introduction|Manual start]]
|IconC=Crystal_Clear_manual.png
}}

</translate>
{{Manual:TOC}}
{{Manual:TOC}}
<translate>


<!--T:2-->
[https://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is a widely popular, open-source programming language, very often used as a scripting language, embedded in applications, as this is the case with FreeCAD. It also has a series of features that makes it specially interesting for us FreeCAD users: It is very easy to learn, specially for people who had never programmed before, and it is embedded in many other applications, which makes it a very valuable tool to learn, as you will be able to use it in many other applications, such as [http://www.blender.org Blender], [http://www.inkscape.org Inkscape] or [http://grass.osgeo.org/ GRASS].
[https://en.wikipedia.org/wiki/Python_%28programming_language%29 Python] is a popular, open source programming language, very often embedded in applications as a scripting language, as is the case with FreeCAD. It has a series of features that make it suitable for us FreeCAD users: It is very easy to learn, especially for people who had never programmed before, and it is embedded in many other applications. This make it a valuable tool to learn, as you will be able to use it in other software, such as [http://www.blender.org Blender], [http://www.inkscape.org Inkscape] or [http://grass.osgeo.org/ GRASS].


<!--T:3-->
FreeCAD makes an extensive use of Python. With it, you can access and control almost any feature of FreeCAD. You can for example create new objects, modify their geometry, analyze their contents, or even create new interface controls, tools and panels. Some workbenches of FreeCAD and most of the addon workbenches are fully programmed in python. FreeCAD has an advanced python console, available from menu '''View->Panels->Python console'''. It is often useful to perform operations for which there is no toolbar button yet, or to check shapes for problems, or to perform repetitive tasks:
FreeCAD makes extensive use of Python. With it, you can access and control almost any feature of FreeCAD. For example, you can create new objects, modify their geometry, analyze their contents, or even create new interface controls, tools and panels. Some FreeCAD workbenches and most of the addon workbenches are fully programmed in Python. FreeCAD has an advanced Python console, available from menu '''View → Panels → Python console'''. It is often useful to perform operations for which there is no toolbar button yet, or to check shapes for problems, or to perform repetitive tasks:


<!--T:4-->
[[Image:Exercise_python_01.jpg]]
[[Image:Exercise_python_01.jpg]]


<!--T:5-->
But the python console also has another very important use: Everytime you press a toolbar button, or perform other operations in FreeCAD, some python code is printed in the console and executed. By leaving the Python console open, you can litterally see the python code unfold as you work, and in no time, almost without knowing it, you will be learning some python language.
But the Python console has another very important use: Every time you press a toolbar button, or perform other operations in FreeCAD, some Python code is printed in the console (if the option to {{MenuCommand|Show script commands in Python console}} is enabled in {{MenuCommand|Edit → Preferences → Python → Macro}}) and executed. By leaving the Python console open, you can literally see the Python code unfold as you work, and in no time, almost without knowing it, you will find yourself learning some of the Python language.


<!--T:6-->
FreeCAD also has a [[Macros|macros system]], which allows you to record actions to be replayed later. This system also uses the Python console, by simply recording everything that is done in it.
FreeCAD also has a [[Macros|macros system]], which allows you to record actions to be replayed later. This system also uses the Python console, by simply recording everything that is done in it.


<!--T:7-->
In this chapter, we will discover very generally the Python language. If you are interested in learning more, the FreeCAD documentation wiki has an extensive section related to [[Power_users_hub|python programming]].
In this chapter, we will discover very generally the Python language. If you are interested in learning more, the FreeCAD documentation wiki has an extensive section related to [[Power_users_hub|Python programming]].


=== Writing python code ===
=== Writing Python code === <!--T:8-->


<!--T:9-->
There are two easy ways to write python code in FreeCAD: From the python console (menu '''View -> Panels -> Python Console'''), or from the Macro editor (menu '''Tools -> Macros -> New'''). 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 launched from the same Macros window.
There are two easy ways to write Python code in FreeCAD: From the Python console ({{MenuCommand|View → Panels → Python Console}}), or from the Macro editor ({{MenuCommand|Tools → Macros → New}}). In the console, you write Python commands one by one, which are executed when you press return, while macros can contain a more complex script made of several lines, which is executed only when the macro is launched from the same Macros window.


<!--T:10-->
In this chapter, you will be able to use both methods, but it is highly recommended to use the Python Console, since it will immediately inform you of any error you could do while typing.
In this chapter, you will be able to use both methods, but it is highly recommended to use the Python Console, since it will immediately inform you of any errors you make while typing.


<!--T:11-->
If this is the first time you are doing Python coding, consider reading this short [[Introduction_to_Python|introduction to Python programming]] before going further, it will make the basic concepts of Python clearer.
If this is your first time using Python, consider reading this short [[Introduction_to_Python|introduction to Python programming]] before going any further, it will make the basic concepts of Python clearer.


=== Manipulating FreeCAD objects ===
=== Manipulating FreeCAD objects === <!--T:12-->


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


<!--T:14-->
doc = FreeCAD.newDocument()
doc = FreeCAD.newDocument()


<!--T:15-->
If you type this in the FreeCAD python console, you will notice that as soon as you type "FreeCAD." (the word FreeCAD followed by a dot), 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 "FreeCAD." (the word FreeCAD followed by a dot), a window pops up, allowing you to quickly autocomplete the rest of the 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.


<!--T:16-->
[[Image:Exercise_python_02.jpg]]
[[Image:Exercise_python_02.jpg]]


<!--T:17-->
As soon as you press '''Enter''' our new document will be created. This is similar to pressing the "new document" button on the toolbar. In Python, the dot is used to indicate something that is contained inside something else (newDocument is a function that is inside the FreeCAD module). The window that pops up therefore shows you everything that is contained inside "FreeCAD". If you would add a dot after newDocument, instead of the parentheses, it would show you everything that is contained inside the newDocument function. The parentheses are mandatory when you are calling a Python function, such as this one. We will illustrate that better below.
As soon as you press '''Enter''' our new document will be created. This is similar to pressing the "new document" button on the toolbar. In Python, the dot is used to indicate something that is contained inside something else (newDocument is a function that is inside the FreeCAD module). The window that pops up therefore shows you everything that is contained inside "FreeCAD". If you would add a dot after newDocument, instead of the parentheses, it would show you everything that is contained inside the newDocument function. The parentheses are mandatory when you are calling a Python function, such as this one. We will illustrate that better below.


<!--T:18-->
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. Let's see what we can do with it. Type the following and explore the available options:


<!--T:19-->
doc.
doc.


<!--T:20-->
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:
Usually names that begin with an upper-case letter are attributes: they contain a value. 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 use of the module, and you should ignore them. Let's use one of the methods to add a new object to our document:


<!--T:21-->
box = doc.addObject("Part::Box","myBox")
box = doc.addObject("Part::Box","myBox")


<!--T:22-->
Our box is added in the tree view, but nothing happens in the 3D view yet, because when working from Python, the document is never recomputed automatically. We must do that manually, whenever we need:
Our box is added in the tree view, but nothing happens in the 3D view yet, because when working from Python, the document is never recomputed automatically. We must do that manually, whenever required:


<!--T:23-->
doc.recompute()
doc.recompute()


<!--T:24-->
Now our box appeared in the 3D view. Many of the toolbar 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 now adding a sphere with the appropriate button in the Part Workbench, and you will see the two lines of python code being executed one after the other.
Now our box has appeared in the 3D view. Many of the toolbar buttons that add objects in FreeCAD actually do two things: add the object, and recompute. Try now adding a sphere with the appropriate button in the Part Workbench, and you will see the two lines of Python code being executed one after the other.


<!--T:25-->
You can get a list of all possible object types like Part::Box:
You can get a list of all possible object types like Part::Box:


<!--T:26-->
doc.supportedTypes()
doc.supportedTypes()


<!--T:27-->
Now let's explore the contents of our box:
Now let's explore the contents of our box:


<!--T:28-->
box.
box.


<!--T:29-->
You'll immediately see a couple of very interesting things such as:
You'll immediately see a couple of very interesting things such as:


<!--T:30-->
box.Height
box.Height


<!--T:31-->
This will print the current height of our box. Now let's try to change that:
This will print the current height of our box. Now let's try to change that:


<!--T:32-->
box.Height = 5
box.Height = 5


<!--T:33-->
If you select your box with the mouse, you will see that in the properties panel, under the '''Data''' tab, our '''Height''' property appears with the new value. All properties of a FreeCAD object that appear in the '''Data''' and '''View''' tabs are directly accessible by python too, by their names, like we did with the Height property. Data properties are accessed directly from the object itself, for example:
If you select your box with the mouse, you will see that in the properties panel, under the '''Data''' tab, our '''Height''' property appears with the new value. All properties of a FreeCAD object that appear in the '''Data''' and '''View''' tabs are directly accessible by Python too, by their names, like we did with the Height property. Data properties are accessed directly from the object itself, for example:


<!--T:34-->
box.Length
box.Length


<!--T:35-->
View properties are stored inside a '''ViewObject'''. Each FreeCAd object possesses a ViewObject, which stores the vieual properties of the object. When running FreeCAD without its Graphical Interface (for example when launching it from a terminal with the -c command line option, or using it from another Python script), the ViewObject is not available, since there is no visual at all.
View properties are stored inside a '''ViewObject'''. Each FreeCAD object possesses a ViewObject, which stores the visual properties of the object. When running FreeCAD without its Graphical Interface (for example when launching it from a terminal with the -c command line option, or using it from another Python script), the ViewObject is not available, since there is no visual at all.


<!--T:36-->
For example, to access the line color of our box:
Try the following example to access the line color of our box:


<!--T:37-->
box.ViewObject.LineColor
box.ViewObject.LineColor


=== Vectors and Placements ===
=== Vectors and Placements === <!--T:38-->


<!--T:39-->
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 much more. In FreeCAD vectors work like this:
Vectors are a 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 much more. In FreeCAD vectors work like this:


<!--T:40-->
myvec = FreeCAD.Vector(2,0,0)
myvec = FreeCAD.Vector(2,0,0)
print(myvec)
print(myvec)
prnimarkdownt(myvec.x)
print(myvec.x)
print(myvec.y)
print(myvec.y)
othervec = FreeCAD.Vector(0,3,0)
othervec = FreeCAD.Vector(0,3,0)
Line 86: Line 134:




<!--T:41-->
Another common feature of FreeCAD objects is their '''Placement'''. As we saw in earlier chapters, each object has a Placement property, which contains the position (Base) and orientation (Rotation) of the object. It is easy to manipulate from Python, for example to move our object:
Another common feature of FreeCAD objects is their '''Placement'''. As we saw in earlier chapters, each object has a Placement property, which contains the position (Base) and orientation (Rotation) of the object. These properties are easy to manipulate from Python, for example to move our object:


<!--T:42-->
print(box.Placement)
print(box.Placement)
print(box.Placement.Base)
print(box.Placement.Base)
box.Placement.Base = sumvec
box.Placement.Base = sumvec
Line 94: Line 144:
otherpla.Base = FreeCAD.Vector(5,5,0)
otherpla.Base = FreeCAD.Vector(5,5,0)
box.Placement = otherpla
box.Placement = otherpla


<!--T:43-->
'''Read more'''
'''Read more'''


<!--T:44-->
* [https://www.python.org/ Python]
* [https://www.python.org Python]
* [[Macros|Working with Macros]]
* [[Macros|Macros]]
* [[Introduction_to_Python|Introduction to Python scripting]]
* [[Python_scripting_tutorial|Using Python in FreeCAD]]
* [[Introduction_to_Python|Introduction to Python]]
* [[Power_users_hub|The Python scripting wiki hub]]
* [[Python_scripting_tutorial|Python scripting tutorial]]
* [[Power_users_hub|Power users hub]]


<!--T:46-->
{{Docnav
|[[Manual:Creating_renderings|Creating renderings]]
|[[Manual:Creating_and_manipulating_geometry|Creating and manipulating geometry]]
|[[Manual:Introduction|Manual start]]
|IconC=Crystal_Clear_manual.png
}}


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

Latest revision as of 13:19, 24 January 2024

Python is a popular, open source programming language, very often embedded in applications as a scripting language, as is the case with FreeCAD. It has a series of features that make it suitable for us FreeCAD users: It is very easy to learn, especially for people who had never programmed before, and it is embedded in many other applications. This make it a valuable tool to learn, as you will be able to use it in other software, such as Blender, Inkscape or GRASS.

FreeCAD makes extensive use of Python. With it, you can access and control almost any feature of FreeCAD. For example, you can create new objects, modify their geometry, analyze their contents, or even create new interface controls, tools and panels. Some FreeCAD workbenches and most of the addon workbenches are fully programmed in Python. FreeCAD has an advanced Python console, available from menu View → Panels → Python console. It is often useful to perform operations for which there is no toolbar button yet, or to check shapes for problems, or to perform repetitive tasks:

But the Python console has another very important use: Every time you press a toolbar button, or perform other operations in FreeCAD, some Python code is printed in the console (if the option to Show script commands in Python console is enabled in Edit → Preferences → Python → Macro) and executed. By leaving the Python console open, you can literally see the Python code unfold as you work, and in no time, almost without knowing it, you will find yourself learning some of the Python language.

FreeCAD also has a macros system, which allows you to record actions to be replayed later. This system also uses the Python console, by simply recording everything that is done in it.

In this chapter, we will discover very generally the Python language. If you are interested in learning more, the FreeCAD documentation wiki has an extensive section related to Python programming.

Writing Python code

There are two easy ways to write Python code in FreeCAD: From the Python console (View → Panels → Python Console), or from the Macro editor (Tools → Macros → New). In the console, you write Python commands one by one, which are executed when you press return, while macros can contain a more complex script made of several lines, which is executed only when the macro is launched from the same Macros window.

In this chapter, you will be able to use both methods, but it is highly recommended to use the Python Console, since it will immediately inform you of any errors you make while typing.

If this is your first time using Python, consider reading this short introduction to Python programming before going any further, it will make the basic concepts of Python clearer.

Manipulating FreeCAD objects

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." (the word FreeCAD followed by a dot), a window pops up, allowing you to quickly autocomplete the rest of the 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.

As soon as you press Enter our new document will be created. This is similar to pressing the "new document" button on the toolbar. In Python, the dot is used to indicate something that is contained inside something else (newDocument is a function that is inside the FreeCAD module). The window that pops up therefore shows you everything that is contained inside "FreeCAD". If you would add a dot after newDocument, instead of the parentheses, it would show you everything that is contained inside the newDocument function. The parentheses are mandatory when you are calling a Python function, such as this one. We will illustrate that better below.

Now let's get back to our document. Let's see what we can do with it. Type the following and explore the available options:

doc.

Usually names that begin with an upper-case letter are attributes: they contain a value. 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 use of the module, and you should ignore them. Let's use one of the methods to add a new object to our document:

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

Our box is added in the tree view, but nothing happens in the 3D view yet, because when working from Python, the document is never recomputed automatically. We must do that manually, whenever required:

doc.recompute()

Now our box has appeared in the 3D view. Many of the toolbar buttons that add objects in FreeCAD actually do two things: add the object, and recompute. Try now adding a sphere with the appropriate button in the Part Workbench, and you will see the two lines of Python code being executed one after the other.

You can get a list of all possible object types like Part::Box:

doc.supportedTypes()

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 will see that in the properties panel, under the Data tab, our Height property appears with the new value. All properties of a FreeCAD object that appear in the Data and View tabs are directly accessible by Python too, by their names, like we did with the Height property. Data properties are accessed directly from the object itself, for example:

box.Length 

View properties are stored inside a ViewObject. Each FreeCAD object possesses a ViewObject, which stores the visual properties of the object. When running FreeCAD without its Graphical Interface (for example when launching it from a terminal with the -c command line option, or using it from another Python script), the ViewObject is not available, since there is no visual at all.

Try the following example to access the line color of our box:

box.ViewObject.LineColor 

Vectors and Placements

Vectors are a 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 much more. In FreeCAD vectors work like this:

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


Another common feature of FreeCAD objects is their Placement. As we saw in earlier chapters, each object has a Placement property, which contains the position (Base) and orientation (Rotation) of the object. These properties are easy to manipulate from Python, for example to move our object:

print(box.Placement)
print(box.Placement.Base)
box.Placement.Base = sumvec
otherpla = FreeCAD.Placement()
otherpla.Base = FreeCAD.Vector(5,5,0)
box.Placement = otherpla

Read more