Python scripting tutorial//プログラミング言語スクリプトチュートリアル

From FreeCAD Documentation
Revision as of 16:06, 28 December 2018 by Luc (talk | contribs) (Created page with "[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]はプログラミング言語で使い方はとても簡単、すぐに修得することができま...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Tutorial
Topic
Programming
Level
Intermediate
Time to complete
Authors
FreeCAD version
Example files
See also
None


Pythonはプログラミング言語で使い方はとても簡単、すぐに修得することができます。オープンソースかつマルチプラットフォームで簡単なシェルスクリプトから非常に複雑なプログラムのプログラミングまでさまざま用途で使用できます。ですがもっとも広く使われている用途はスクリプト言語として使うというものです。これは他のアプリケーションに簡単に組み込むことができるためです。FreeCAD内部でもまさにその様にして使用されています。Pythonコンソール、または自作のスクリプトからFreeCADを操作したり、まだグラフィカルユーザーインターフェイスのツールがない非常に複雑な動作を行わせることもできます。

例えばPythonスクリプトからは次の様な操作を行うことができます;

  • 新しいオブジェクトの作成
  • 既存のオブジェクトの変更
  • それらのオブジェクトの3D表示の変更
  • FreeCADのインターフェイスの変更

FreeCADではPythonを使う複数の方法が存在します:

  • FreeCAD Pythonインタープリター。"コマンドライン"スタイルのインターフェイスでシンプルなコマンドを実行することができます。
  • マクロ。存在しないツールをFreeCADインターフェイスに手軽に追加するのには便利な方法です。
  • 外部スクリプト。より複雑なプログラムに使用できます。例えばワークベンチ全体といったものです。

このチュートリアルでは入門的なサンプルスクリプトをいくつか作成しますが、このWikiにはこれ以外にもたくさんの利用可能なPythonスクリプトについてのドキュメントがあります。もしPythonを使うのが初めてでその機能を知りたいのであれば基礎的なPyton入門もあります。

Pythonのコードを書く

FreeCADでPythonのコードを書く場合には二つの手軽な方法があります:Pythonコンソール(View -> Views -> Python consoleメニューから利用可能)、またはマクロエディター(Tools -> Macros)です。コンソールの場合Pythonコマンドを一つ一つ書いていき、コマンドはリターンキーを押したタイミングで実行されます。一方、マクロでは複数行からできたより複雑なスクリプトを保存できます。このスクリプトはマクロが実行されたタイミングでだけ実行されます。

FreeCADのPythonコンソール

このチュートリアルでは両方の方法を使うことができます。各行を一行ずつPythonコンソールにコピー/ペーストして各行ごとにReturnキーを押すか、コード全体を新しいマクロウィンドウにコピー/ペーストしてください。

FreeCADの調査

さてまずは新しい空のドキュメントを作成しましょう:

doc = FreeCAD.newDocument()

このコマンドをPythonコンソールに入力すると"FreeCAD."と入力した直後に行の残りをすばやく自動補完できるようにウィンドウがポップアップします。さらには自動補完リストの各エントリーにはそれが何を行うものかの説明のツールチップさえ備わっているのです。これを使えば利用可能な関数を簡単に調べることができます。"newDocument"を選択する前に他の利用可能なオプションも見ておいてください。

FreeCADのPythonコンソールの自動補完機能

さて新しいドキュメントが作成されました。これはツールバーの"新しいドキュメント"ボタンを押した場合と同じです。実際はFreeCADのボタンのほとんどは一、二行のPythonコードを実行しているだけに過ぎません。Edit -> Preferences -> General -> Macroにある"show script commands in python console"オプションを設定するとよくわかります。こうするとボタンを押した時に実行されるPythonコードが全てコンソールに表示されます。Pythonで操作を再現する方法を学ぶのにとても便利です。

さあ、ドキュメントに戻りましょう。ドキュメントを使って何ができるのかを確認してみましょう。

doc.

利用可能なオプションを調べてください。通常、大文字から始まる名前は値が保持されている属性で、小文字から始まる名前は"処理を行うための"関数(メソッドとも呼ばれます)です。アンダースコアで始まる名前は通常はモジュールの内部動作のためのもので、気にする必要はありません。それではドキュメントに新しいオブジェクトを追加するためのメソッドの一つを使って見ましょう。

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

何も起きません。なぜでしょう?これはFreeCADが大きな展望に立って作られているからです。いつの日かそれぞれ独立した数百もの複雑なオブジェクトをFreeCADで操作できる時が来るでしょう。どこかを少し変更するだけで大きな影響が現れ、ドキュメント全体を再計算しなければならなくなるかもしれません。それには長い時間がかかることでしょう・・・こういった事情からほとんどのコマンドではシーンが自動的に更新されることはありません。手動で更新を行う必要があるのです:

doc.recompute()

見えましたか?作成したボックスが表示されました!FreeCADのオブジェクト追加ボタンの多くは実のところ2つの処理を行います。オブジェクトの追加と再計算です。もし上で説明した"show script commands in python console"オプションを有効にしていれば今度はGUIのボタンで球を追加してみてください。二行のPythonコードが順番に実行されるのが見て取れるでしょう。

"Part::Box"は何かですって?どうすれば他の種類のオブジェクトを追加できるかですって?これを使うとわかります:

doc.supportedTypes()

さて、作成したボックスの中身を調べてみましょう:

box.

すぐにとても興味をそそられるものがいくつか見つかるでしょう。例えばこれです:

box.Height

これを使うとボックスの現在の高さを表示できます。変更してみましょう:

box.Height = 5

マウスでボックスを選択するとプロパティパネルの"Data"タブに"Height"プロパティが表示されているのがわかるでしょう。ここ(と後で説明する"View"タブ)に表示されるFreeCADオブジェクトのプロパティは全てPythonによって直接アクセスすることができます。アクセスは先ほど"Height"プロパティでやったように名前で行います。ボックスの別の寸法も変更してみてください。

ベクトルと配置

ベクトルは3Dアプリケーションにおいて非常に基礎的な概念です。ベクトルとは3つの数字(x、y、z)のリストで、3D空間ないでの点や位置を表します。ベクトルを使うと加算、減算、投影やその他にも色々なことを行うことができます。FreeCADでは次のようにしてベクトルを使用します:

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

FreeCADオブジェクトに共通する機能の一つが配置です。各オブジェクトはPlacement属性を持ち、そこにはオブジェクトの位置(Base)と方向(Rotation)が保持されています。操作は簡単です。一例として私たちのオブジェクトを動かしてみましょう。

box.Placement.
box.Placement.Base
box.Placement.Base = sumvec

otherpla = FreeCAD.Placement()
box.Placement = otherpla

さて、さらに進む前にいくつかの重要な概念を理解しておく必要があります。

AppとGui

FreeCADは最初、ユーザーインターフェイス無しのコマンドラインアプリケーションとして動作するように作成されていました。その結果、ほとんど全ての物が"幾何"コンポーネントと"表示"コンポーネントに分割されています。コマンドラインモードで動作させている際には幾何部分は存在しますが表示部分は無効化されるています。こうした理由からFreeCADのほとんどのオブジェクトは二つの部分、つまりObjectとViewObjectから構成されています。


このコンセプトの説明のために私たちの立方体を見てください。寸法や位置など立方体の幾何プロパティはObjectの中に保持されています。一方、色や線の太さなどの表示プロパティはViewObjecの中に保持されています。そしてそれがプロパティウィンドウの"Data"タブと"View"タブに対応しているのです。オブジェクトのViewObjecには次のようにしてアクセスすることができます:

vo = box.ViewObject

これで"View"タブのプロパティを変更することもできるようになりました:

vo.Transparency = 80
vo.hide()
vo.show()

FreeCADが起動するとすぐにPythonコンソールは2つの基本モジュールをロードします。FreeCADとFreeCADGuiです(これらにも短縮名のAppとGuiによってアクセスることが可能です)。この二つにはドキュメントとそのオブジェクトを操作するための一般的な機能が保持されています。このコンセプトの説明のためにFreeCADとFreeCADGuiの両方にActiveDocument属性があることを確認してください。これが現在、開かれているドキュメントです。FreeCAD.ActiveDocumentとFreeCADGui.ActiveDocumentは同じオブジェクトではありません。FreeCADドキュメントを¥の二つのコンポーネントであり、異なる属性とメソッドが保持されています。例えばFreeCADGui.ActiveDocument にはActiveViewがありますが、これは現在開かれている3Dビューです。

モジュール

あなたはきっと今、"Part::Box"以外には何ができるんだろう?と思っているに違いありません。FreeCADベースのアプリケーションは多少の違いはあれ空の入れ物です。モジュールがなければできることは新しい空のドキュメントを作ることがせいぜいです。FreeCADの真価はそれに付き従うモジュールなのです。それぞれのモジュールはインターフェイスに新しいワークベンチを付け加えるだけでなく、新しいPythonコマンドや新しいオブジェクト型の追加も行います。それによって複数の異なるオブジェクト型、場合によっては全く互換性のないオブジェクト型まで同じドキュメントに共存させることができるのです。後でこのチュートリアルでも見ていきますが、FreeCADで最も重要なモジュールはPartMeshSketcher、そしてDraftです。

SketcherDraftは両方とも形状の作成と制御にPartモジュールを使用しています。これらで扱われる形状はBRepですが一方のMeshは完全に独立し、独自のオブジェクトを制御します。詳細については下記にあります。

現在のドキュメントでの利用可能な基底オブジェクト型は次のようにしてチェックすることができます:

doc.supportedTypes()

さまざまなFreeCADモジュールはFreeCADに独自のオブジェクト型を追加しますがpythonコンソールでは自動的に読み込まれません。これは起動が遅くなることを防ぐためです。モジュールはそれが必要になった時にのみ読み込まれます。例えばPartモジュールの内部を調べたい時は以下のようにします:

import Part
Part.

しかし今はここまでにしておいてPartモジュールについては後で詳しく説明します。

さて、FreeCADのさまざまなモジュールについて多少は理解できたと思います。コアモジュール(FreeCAD、FreeCADGui)とワークベンチモジュール(Part、Mesh、Sketcher)です。それ以外にも3Dシーンモジュール(pivy)とインターフェイスモジュール(pyqt)という重要なモジュールがありますが、それについても後で説明を行います。

さあ重要なワークベンチモジュールの一つについてもう少し詳しく見て行くことにしましょう。

Mesh

メッシュは非常に単純な3Dオブジェクトで例えばSketchupBlender3D studio Maxで使用されています。メッシュは3つの要素でできています。点(頂点とも呼ばれます)、線(エッジとも呼ばれます)、そして面です。FreeCADを含む多くのアプリケーションでは面は点を三つだけ持つことができます。しかし、もちろん同一平面上にある複数の三角形からなるもっと大きな平面を作ることができます

メッシュは非常に単純なのでそれが短所になることもありますが上にあげたような多くのアプリケーションではむしろ利点になります。単純ゆえに一つのドキュメントの中に数百万ものメッシュを持つことが容易にできるからです。しかしFreeCAD内部ではあまり使われず、ほとんどの場合は他のアプリケーションから出力されたメッシュ形式(.stl、.obj)のオブジェクトをインポートする用途に使われます。またFreeCADが誕生した初めの一ヶ月間はメインテストモジュールとして広く使われました。

MeshオブジェクトとFreeCADオブジェクトは別物です。FreeCADオブジェクトをMeshオブジェクトの入れ物と考えるといいでしょう(後で見るようにPartオブジェクトについても同じことが言えます)。FreeCADにメッシュオブジェクトを追加するためにはまず最初にFreeCADオブジェクトとMeshオブジェクトを作成しなければなりません。それが終わったらFreeCADオブジェクトにMeshオブジェクトを追加します:

import Mesh
mymesh = Mesh.createSphere()
mymesh.
mymesh.Facets
mymesh.Points

meshobj = doc.addObject("Mesh::Feature","MyMesh")
meshobj.Mesh = mymesh
doc.recompute()

標準的な例です。createSphere()メソッドを使って自動で球を作成していますが、もちろん頂点と面を定義してゼロから自作のメッシュを作成することもできます。

メッシュのスクリプト処理についてもっと読む・・・

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 also several different ways to use python in FreeCAD:

  • From the FreeCAD python interpreter, where you can issue simple commands like 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 be used to program much more complex things. like entire Workbenches.

In this tutorial, we'll work on a couple of simple examples to get you started, but there is also 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.

Important! Before proceeding with Python scripting, go to Edit->Prefences->General->Output window and check 2 boxes:

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

Then go to View->Panels and check:

  • Report view

This will save you a lot of aggravation!

Writing python code

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.

The FreeCAD python console

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 Return after each line, or by copying/pasting the entire code in a new Macro window.

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

The autocomplete mechanism of the FreeCAD python console

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

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:

doc.recompute()

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.

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

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

myvec = FreeCAD.Vector(2,0,0)
myvec
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 attributes, which contains the position (Base) and orientation (Rotation) 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 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:

vo = box.ViewObject

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

vo.Transparency = 80
vo.hide()
vo.show()

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

doc.supportedTypes()

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:

import Part
Part.

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

Mesh

Meshes are a very simple kind of 3D objects, 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. But of course nothing prevents you from having a bigger plane face made of several coplanar triangles.

Meshes are simple, this can be a bad thing, but for many applications such as those mentioned above, it turns to be an advantage, because they are so simple that you can easily have millions of them in a single document. In FreeCAD, though, they have less use, and are mostly there so you can import objects in mesh formats (.stl, .obj) from other applications. It 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 (like, we'll see below, for Part objects too). 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.
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 automatically create a sphere, but you can very well 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 of the whole FreeCAD. It allows to create and manipulate BRep objects. This kind of object, unlike meshes, can have a wide variety of components. To resume a bit, Brep means Boundary Representation. which means that they are defined by their surfaces, which enclose and define an inner volume. These surface can be a variety of things, such as plane faces or very complex NURBS surfaces. They also carry the concept of volume.

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:

import Part
myshape = Part.makeSphere(10)
myshape.
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 add a shape to it, so you can skip the 3 last lines above:

Part.show(myshape)

By exploring the contents of myshape, you will notice many interesting available subcomponents such as Faces, Edges, Vertexes, Solids or 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 or Draft, which also create Part objects, but add parameters to it, or even carry a whole new way to handle the Part geometry in them. Our box example above, is a perfect example of parametric object. All you need, to define the box, is to specify a couple of parameters, such as 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 a couple of 2D parametric objects 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:

import Draft
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, buttons around the 3D view. Qt provides a module, called 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:

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

See 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, but also has a couple of very 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 couple of lines of python.

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 then be added to a toolbar and be launched from a simple mouse click. FreeCAD provides you with a simple text editor (Macro -> Macros -> Create) where you can write or paste scripts. Once it is done, the Tools -> Customize -> Macros allow you 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!

Introduction to Python
FreeCAD Scripting Basics