Python scripting tutorial/ru: Difference between revisions

From FreeCAD Documentation
No edit summary
No edit summary
Line 18: Line 18:
* Изменить интерфейс FreeCAD.
* Изменить интерфейс FreeCAD.


Существует несколько способов использования Python в FreeCAD:
<div class="mw-translate-fuzzy">
* Из [[FreeCAD Scripting Basics/ru|Интерпретатора Python в FreeCAD]], где вы можете запускать простые команды, симулируя интерфейс командной строки
Существует несколько способов использования python в FreeCAD:
* Из [[macros/ru|макросов]], которые являются удобным способом быстрого добавления недостающего функционала в интерфейс FreeCAD
* Из [[FreeCAD Scripting Basics | Интерпретатора python в FreeCAD]], где вы можете запускать простые команды, симулируя интерфейс командной строки
* Из внешних скриптов, которые можно использовать для создания довольно сложных решений, даже [[Workbenches/ru|верстаков]].
* Из [[macros|макросов]], которые являются удобным способом быстрого добавления недостающего функционала в интерфейс FreeCAD
* Из внешних скриптов, которые можно использовать для программирования более сложных вещей, таких как [[Workbenches|Верстаки]].
</div>


<div class="mw-translate-fuzzy">
<div class="mw-translate-fuzzy">

Revision as of 07:58, 25 May 2020

Введение

Python - это язык программирования, относительно простой в изучении и понимании. Он является многоплатформенным языком с открытым исходным кодом и может использоваться в разных целях: от программирования простых скриптов до очень сложных программ. Но он наиболее распространен как язык сценариев, внедряемых в другие приложения. Так он используется и внутри FreeCAD. Из консоли Python или с помощью собственных скриптов вы можете управлять FreeCAD, заставляя его выполнять очень сложные операции.

Например, из сценария Python вы можете:

  • Создать новые объекты.
  • Изменить существующие объекты.
  • Изменить трехмерное представление этих объектов.
  • Изменить интерфейс FreeCAD.

Существует несколько способов использования Python в FreeCAD:

  • Из Интерпретатора Python в FreeCAD, где вы можете запускать простые команды, симулируя интерфейс командной строки
  • Из макросов, которые являются удобным способом быстрого добавления недостающего функционала в интерфейс FreeCAD
  • Из внешних скриптов, которые можно использовать для создания довольно сложных решений, даже верстаков.

В этом руководстве мы рассмотрим несколько простых примеров, которые помогут вам начать работу. В этой вики также имеется гораздо больше документации по python сценариям. Если вы абсолютный новичок в python и хотите понять, как это работает, у нас есть базовый курс Введение в Python.

"'Важно!'" Перед написанием Python сценариев, перейдите в окно Edit-> Prefences-> General-> Output и проверьте 2 пункта:

  • Перенаправить внутренний вывод Python в отчет
  • Перенаправить внутренние ошибки Python в отчет

Затем перейдите в View-> Panels и проверьте:

  • Отчет

Это сэкономит вам много нервов!

Написание python кода

Существует два простых способа написания Python кода в FreeCAD: в python консоли (меню «Вид-> Панели -> Консоль Python») или из редактора макросов (Инструменты -> Макросы). В консоли вы последовательно пишете python команды, которые выполняются при нажатии return. Макросы могут содержать более сложный много-строчный скрипт, который выполняется во время запуска макроса.

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

В этом руководстве описаны оба метода: либо путем копирования / вставки по одной строчке в python консоли и нажатия Return в конце строки, либо путем копирования / вставки всего кода в новое окно макроса.

Изучение FreeCAD

Начнем с создания нового пустого документа:

Let's start by creating a new empty document:

doc = FreeCAD.newDocument()

Если Вы вводите это в консоли Python FreeCADа, то заметите, что как только Вы ввели FreeCAD. (слово FreeCAD с последующей точкой), появится окно, позволяющее быстро автозаполнить продолжение строки. Даже лучше, каждый ввод в списке автодополнения содержит подсказку. Это облегчает раскрытие имеющейся функциональности. Перед выбором newDocument, взгляните на другие доступные опции.

+

Механизм автозаполнения python консоли FreeCAD

Теперь наш новый документ будет создан. Это похоже на нажатие кнопки «новый документ» на панели инструментов. Фактически, большинство кнопок в FreeCAD ничего не делают, кроме выполнения строки или двух python кода. Еще лучше, вы можете установить параметр в Edit-> Preferences-> General-> Macro, чтобы «показать команды сценария в консоли python». Это будет выводить в консоль весь python код, который выполняется при нажатии кнопок. Очень полезно узнать, как воспроизводить действия в python.

Теперь вернёмся назад в документ и посмотрим, что мы можем с ним сделать:

doc.

Изучим доступные варианты. Обычно имена, начинающиеся с заглавной буквы, это атрибуты, они содержат значения, а имена с маленькой буквы являются функциями (называемые так же методами), они "что-то делают". Имена, начинающиеся с подчёркиваний, обычно используются для внутренних нужд модуля, и Вам не следует обращать на них внимание. Используем один из методов для добавления в документ нового объекта:

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

Ничего не произошло. Почему? Потому что FreeCAD создан для больших проектов. Однажды он будет работать с сотнями сложных взаимосвязанных объектов. Возможно, что внесение небольшого изменения может иметь большое значение, вам может потребоваться пересчитать весь документ, что может занять много времени ... По этой причине почти никакая команда не обновляет сцену автоматически. Вы должны сделать это вручную:

doc.recompute()

Теперь наш куб появился в окне трёхмерного вида. Большинство кнопок панелей инструментов фактически делают две вещи: добавляют объект и выполняют пересчёт. Если Вы включите в настройках опцию "Показывать команды скриптов в консоли python" и попробуете добавить сферу с соответствующей кнопкой, Вы увидите две строки Python кода, выполняемые одна за другой.

Теперь рассмотрим содержимое нашего куба:

box.

Вы немедленно увидите несколько очень интересных вещей вроде этого:

box.Height

Это покажет текущую высоту нашего куба. Теперь попробуем её изменить:

box.Height = 5

Если вы выберете куб с помощью мыши, вы увидите, что Property editor на вкладке Данные появится параметр ДанныеHeight. Все свойства объекта FreeCAD, которые появляются там (а также на вкладке Вид, подробнее об этом позже), напрямую доступны также для Python по их именам, аналогично параметру ДанныеHeight. Попробуйте изменить другие размеры окна.

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 ДанныеPlacement property, which contains the ДанныеBase (position) and Данные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.

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.

Modules

The true power of FreeCAD lies in its faithful modules. 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.

Mesh

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

Part

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

Draft

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)

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

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.

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