Python scripting tutorial/zh-cn

Python是一门非常简单易学的编程语言. 它集开源、多平台于一身，且可以摆脱其他各种工具独立使用，借助简单的shell脚本编程即可实现非常复杂的程序. 但是其最广泛的用处是作为一种脚本语言，因为它易于嵌入其他的应用之中. 这便是在FreeCAD中用这种语言的原因. 您可以通过python控制台或自定义脚本的方式来使用FreeCAD，这也是在非图形用户界面工具下执行非常复杂动作的方法.

例如，通过python脚本您可以：
 * 创建新的对象
 * 修改已存在的对象
 * 修改那些对象的3D表示
 * 修改FreeCAD接口

在FreeCAD中有以下几种使用python的不同方式：
 * 在FreeCAD的python解释器中使用脚本. 在此，您可以通过类似于“命令行”样式的界面来发出简单的命令
 * 在宏中使用脚本. 这是一种将缺失的工具快速添加至FreeCAD界面的便捷方法
 * 借助外部脚本. 这可用来编写更复杂的程序. 比如编写整个工作台.

在本教程中，我们将通过若干简单的示例来令您入门，除此之外，本wiki中还存在更多关于python脚本的文档. 如果您是一位python新手，希望理解它的工作原理，我们也为您提供了较为基础的Python简介.

重要提示! 在用Python脚本进行处理之前，前往窗口并选中两个选择框： 再去往并选中： 这将把您从大量恼人的事情之中解救出来！
 * Redirect internal Python output to report view
 * Redirect internal Python errors to report view
 * Report view

编写python代码
FreeCAD提供了两种环境供用户方便地编写python代码：python控制台(可从View → Panels → Python console菜单开启)或宏编辑器(Tools → Macros). 在控制台中，您可以逐行地编写python命令，按下回车键后即刻执行. 而宏中则可容纳更复杂的多行脚本，只有在执行宏时才会执行相应代码.



在此教程中，您可以使用下列两种方式编辑代码：通过在python控制台中单行复制/粘贴代码并按下来逐行执行，或在新的宏窗口中复制/粘贴全部代码一次性执行.

探索FreeCAD
让我们首先来创建一个新的空文档：

如果您在FreeCAD的python控制台中输入这些内容，会发现仅需敲入“FreeCAD.”就会弹出一个窗口，让您快速地自动补齐剩下的代码. 更强大的是，自动补齐列表中的每一项都有对应的工具提示来解释其具体使用细节. 这便于用户更轻松地浏览可用的各种函数功能. 在选择"newDocument"之前，您可以顺便查看其它存在的可选项.



现在我们就会创建一个新文档. 这就类似于按下工具栏上的"new document"按钮. 事实上，FreeCAD中的大部分按钮实现的功能也就相当于执行一、两行python代码. 更妙的是，您可以通过设置中的"show script commands in python console"选项，在控制台中查看按下每个按钮时所执行的python代码. 这对于学习如何用python复现FreeCAD的各种动作是极为有益的.

现在我们把视线重归文档本身. 来看看可以对它进行哪些操作：

借此即可阅览各种与文档有关的可选项. 通常以大写字母开头为名的是属性，而已小写字母开头的是函数（或称方法），函数会执行“某些操作”. 以一个下划线开头的名称通常为模块的内部函数，无需在上面花太多心思. 现在，让我们来使用特定方法为刚刚新建的文档添加一个新对象：

什么都没有发生. 喂神马？这其实是FreeCAD为整体大局而定的策略. 在一天里，它将处理数百复杂的对象，而所有的对象又彼此依赖. 仅做出一点儿小的改动就可能牵一发而动全身，您也许只想对整个文档重新计算一次，但可能却需要花费很长的时间……出于这个原因，基本上没有任何命令会自动更新场景. 因此，您必须手动来实现这件事：

看到了吗？现在我们创建的立方体粗线惹！FreeCAD中用于添加对象的大多按钮实际上都做了两件事：添加对象，并重新进行计算. 如果您按前文所述开启了"show script commands in python console"选项，并试着用GUI按钮添加一个球体，您将看到也执行了上述python代码.

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

Now let's explore the contents of our box:

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

This will print the current height of our box. Now let's try to change that:

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.

Vectors and Placements
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:

Another common feature of FreeCAD objects is their 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:

Now you must understand a couple of important concepts before we get further.

App and Gui
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.

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:

Now you can also change the properties of the "View" tab:

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

Modules
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, Mesh, Sketcher and Draft.

Sketcher and Draft both use the Part module to create and handle their geometry, which are BRep 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:

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:

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

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.

Now it's time to explore a bit deeper the important ones, which are the workbench modules.

网格
Meshes are a very simple kind of 3D object, used for example by Sketchup, Blender or 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.

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:

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.

Read more about mesh scripting...

Part
The Part Module is the most powerful module in the whole of FreeCAD. It allows you to create and manipulate 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.

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

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:

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

Draft
FreeCAD features many more modules, such as Sketcher and 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 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 work not only on Draft-made objects, but on any Part object. To explore what is available, simply do:

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. 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. We can therefore easily directly 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...

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 easily from FreeCAD? There is an easy mechanism for that, called 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.

Now you are ready for more in-depth FreeCAD scripting. Head on to the Power users hub!