Python scripting tutorial

From FreeCAD Documentation
Revision as of 07:36, 30 August 2011 by Splineman (talk | contribs)

Python is a programming language, very simple to use and very fast to learn. It is open-source, multi-platform, and can be used alone for a wide array of things, from programming simple shell scripts to very complex programs. But one of its most widespread uses is as a scripting language, since it is easy to embed in other applications. That's exactly how it is used inside FreeCAD. From the python console, or from your custom scripts, you can pilot FreeCAD, and make it perform very complex actions for which there is still no graphical user interface tool.

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

Writing python code

There are two easy ways to write python code in FreeCAD: From the python console (available from the View -> Views -> 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.

TO BE CONTINUED

Available translations of this page: