Руководство: Простое введение

From FreeCAD Documentation
Revision as of 08:30, 11 April 2017 by Baritone (talk | contribs) (Created page with "Есть два простых способа написания кода python в FreeCAD: из консоли python (меню '''Вид -> Панели -> Консоль P...")

Python - популярный у многих язык программирования с открытыми исходниками, часто используемых как скриптовый язык, встраиваемый в приложения, как в случае FreeCAD. У него так же много возможностей, интересных для пользователей FreeCAD: он лёгок в изучении, особенно для людей, ранее не программировавших, и встроен во множество других приложений, что делает его очень ценным для изучения, поскольку Вы сможете использовать его во множестве других приложений, таких как Blender, Inkscape или GRASS.

FreeCAD широко использует Python. С его помощью Вы можете иметь доступ и управлять практически любой возможностью FreeCAD. Вы можете, например, создавать новые объекты, модифицировать его геометрию, анализировать содержимое, или даже создавать новые элементы управления, инструменты и панели. Некоторые верстаки FreeCAD и большинство дополнительных верстаков запрограммированы полностью на python. У FreeCAD есть совершенная консоль python, доступная из меню Вид->Панели->Консоль Python. Она часто полезна для выполнения операций, для которых пока нет кнопок инструментальных панелей, или проверки фигур на ошибки, или выполнения повторяющихся задач:

Но консоль python можно использовать и по-другому: каждый раз как Вы нажмёте на кнопку в панели инструментов или выполните в FreeCAD другую операцию, в консоли появляется и выполняется код python. Оставляя консоль Python открытой, Вы можете точно видеть как разворачивается код python в процессе работы, и довольно быстро, почти не замечая, Вы сможете выучить язык python.

У FreeCAD так же есть система макросов, позволяющая записывать действия для последующего воспроизведения. Эта система так же использует консоль Python, просто записывая всё, что им сделано.

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

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

Есть два простых способа написания кода python в FreeCAD: из консоли python (меню Вид -> Панели -> Консоль Python), или из редактора макросов (меню Tools -> Macros -> New). В консоли Вы пишете команды python одну за одной, и они выполняются после нажатия кнопки Return, в то время как макросы могут содержать сложный скрипт из нескольких линий, исполняемый лишь когда макрос запущен из того же окна макросов.

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.

If this is the first time you are doing Python coding, consider reading this short introduction to Python programming before going further, it will make the basic concepts of Python clearer.

Манипуляция объектами 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." (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.

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:

doc.

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:

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 we need:

doc.recompute()

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.

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.

For example, to access the line color of our box:

box.ViewObject.LineColor 

Векторы и места размещения

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:

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

Other languages: