Extra python modules/ru

Overview
This page lists several additional Python modules or other pieces of software that can be downloaded freely from the internet, and add functionality to your FreeCAD installation.

PySide (previously PyQt)

 * homepage (PySide): http://qt-project.org/wiki/PySide
 * license: LGPL
 * optional, but needed by several modules: Draft, Arch, Ship, Plot, OpenSCAD, Spreadsheet

PySide (previously PyQt) is required by several modules of FreeCAD to access FreeCAD's Qt interface. It is already bundled in the windows verison of FreeCAD, and is usually installed automatically by FreeCAD on Linux, when installing from official repositories. If those modules (Draft, Arch, etc) are enabled after FreeCAD is installed, it means PySide (previously PyQt) is already there, and you don't need to do anything more.

Note: FreeCAD progressively moved away from PyQt after version 0.13, in favour of PySide, which does exactly the same job but has a license (LGPL) more compatible with FreeCAD.

Linux
The simplest way to install PySide is through your distribution's package manager. On Debian/Ubuntu systems, the package name is generally python-PySide, while on RPM-based systems it is named pyside. The necessary dependencies (Qt and SIP) will be taken care of automatically.

Windows
The program can be downloaded from http://qt-project.org/wiki/Category:LanguageBindings::PySide::Downloads. You'll need to install the Qt and SIP libraries before installing PySide (to be documented).

MacOS
PySide on Mac can be installed via homebrew or port. See Install dependencies for more information.

Usage
Once it is installed, you can check that everything is working by typing in FreeCAD Python console:

To access the FreeCAD interface, type:

Now you can start to explore the interface with the dir command. You can add new elements, like a custom widget, with commands like:

Working with Unicode:

Working with QFileDialog and OpenFileName:

Working with QFileDialog and SaveFileName:

Example of transition from PyQt4 and PySide
PS: these examples of errors were found in the transition from PyQt4 to PySide and these corrections were made, other solutions are certainly available with the examples above

To access the FreeCAD interface, type: You can add new elements, like a custom widget, with commands like:

Working with Unicode:

Working with QFileDialog and OpenFileName:

Working with QFileDialog and SaveFileName:

The MessageBox:

Working with setProperty (PyQt4) and setValue (PySide)

replace with:

Working with setToolTip

replace with:

or:

Additional documentation

 * Qt official documentation site

Pivy

 * homepage: https://bitbucket.org/Coin3D/coin/wiki/Home
 * license: BSD
 * optional, but needed by several modules of FreeCAD: Draft, Arch

Pivy is a needed by several modules to access the 3D view of FreeCAD. On windows, Pivy is already bundled inside the FreeCAD installer, and on Linux it is usually automatically installed when you install FreeCAD from an official repository. On macOS, unfortunately, you will need to compile pivy yourself.

Prerequisites
I believe before compiling Pivy you will want to have Coin and SoQt installed.

I found for building on Mac it was sufficient to install the Coin3 binary package. Attempting to install coin from MacPorts was problematic: tried to add a lot of X Windows packages and ultimately crashed with a script error.

For Fedora I found an RPM with Coin3.

SoQt compiled from source fine on Mac and Linux.

Debian & Ubuntu
Начиная с Debian Squeeze и Ubuntu Lucid, pivy стал доступен напрямую через официальные репозитории, экономя ваше время. В то же время вы можете скачать один из пакетов что мы сделали (для debian и ubuntu karmic) доступных на странице Загрузок, или скомпилировать их самостоятельно.

Лучший способ скомпилировать pivy просто вытянуть debian пакет с исходными кодами для pivy и сделать пакет с помощью debuild. Это тот же исходный код что и на оффициальном сайте pivy, но люди debian исправили несколько ошибок. Он также хорошо компилируется в ubuntu karmic из: http://packages.debian.org/squeeze/python-pivy (скачайте .orig.gz и .diff.gz файл, распокуйте оба, добавте .diff к исходному коду: перейдите к каталогу с распакованными кодами pivy, и примените .diff патч:

затем

теперь у вас есть правильно собраный pivy в оффициально устанавливаемых пакетах. Теперь, просто установите пакет с помощью gdebi.

Другие linux дистрибутивы
Сперва получите код из официального репозитория проекта:

As of March 2012, the latest version is Pivy-0.5.

Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25, не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз http://www.swig.org. Распакуйте и в командной строке (под root-ом):

Сборка занимает всего несколько секунд.

Alternatively, you can try building with a more recent SWIG. As of March 2012, a typical repository version is 2.0.4. Pivy has a minor compile problem with SWIG 2.0.4 on macOS (see below) but seems to build fine on Fedora Core 15.

After that go to the pivy sources and call

which creates the source files. Note that build can produce thousands of warnings, but hopefully there will be no errors.

This is probably obsolete, but you may run into a compiler error where a 'const char*' cannot be converted in a 'char*'. To fix that you just need to write a 'const' before in the appropriate lines. There are six lines to fix.

After that, install by issuing (as root):

That's it, pivy is installed.

MacOS
These instructions may not be complete. Something close to this worked for OS 10.7 as of March 2012. I use MacPorts for repositories, but other options should also work.

As for linux, get the latest source:

If you don't have hg, you can get it from MacPorts:

Then, as above you need SWIG. It should be a matter of:

I found I needed also:

As of March 2012, MacPorts SWIG is version 2.0.4. As noted above for linux, you might be better off downloading an older version. SWIG 2.0.4 seems to have a bug that stops Pivy building. See first message in this digest

This can be corrected by editing the 2 source locations to add dereferences: *arg4, *arg5 in place of arg4, arg5. Now Pivy should build:

Windows
Предполагается использование Visual Studio 2005 или позднии версии вы предется открыть командную строку 'Visual Studio 2005 Command prompt' из меню Tools. Если Python интерпритатор ещё не прописан в системном пути, сделайте это

Чтобы получить работающий pivy вы должны получить последнюю версию исходников из репозитория проекта:

Затем вам понадобится инструмент называемыйd SWIG для создания C++ кода для Python привязок. Рекомендуется использовать версию SWIG 1.3.25, не последнюю версию, потому как на данный момент pivy корректно работает только с 1.3.25. Скачайте 1.3.25 tarball с исходными кодамииз http://www.swig.org. Затем распакуйте его и в командной строке добавте к системному пути

и установите COINDIR на соответсвующий путь

В Windows pivy конфигурационный файл нахотится в SoWin вместо SoQt по умолчанию. Мне не удалось найти очевидный способ собрать с SoQt, поэтому я изменил файл непосредственно setup.py. В 200 строке удалите часть 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (не удалйте закрывающиеся скобки).

После чего отправляйтесь к исходным кодам pivy и введите команду

которая создаст исходные файлы. Вы можете столкнуться с ошибками компилятора -несколько заголовочных файлов не может быть найдено. В этом случае отрегулируйте INCLUDE переменную

если нет заголовочных файлов SoQt на месте, также с заголовками Coin

и в конце Qt заголовочные файлы

Если вы используете Express Edition версию Visual Studio вы можете получить исключение python keyerror. В этом случае Вам необходимо изменить кое-что в msvccompiler.py расположенный в месте кужа вы установили Python.

шагом марш на 122 строку и замените строку

на

Повторите сборку снова. Если вы получили вторую ошибку, вроде

вы должны поменять 128 строку

на

Повторите сборку снова. Если вы опять получили ошибку

проверте пересеменные окружения DISTUTILS_USE_SDK и MSSDK с помощью

Если они еще не установлены, то просто установите например, до 1

Вы можете столкнуться при компиляции с ошибкой 'const char*' cannot be converted in a 'char*'. Чтобы исправить это вам необходимо написать 'const' перед следующей строкой(char*). Исправте ещё шесть строк. После чего, скопируйте созданный pivy каталог, в место где python интрепритатор FreeCAD сможет найти его.

Usage
To check if Pivy is correctly installed:

Чтобы Pivy получил доступ FreeCAD древу сцен сделайте следующие:

Теперь вы можете изучать FCSceneGraph с помощью команды dir.

Additonal Documentation
Unfortunately documentation about pivy is still almost nonexistant on the net. But you might find Coin documentation useful, since pivy simply translate Coin functions, nodes and methods in Python, everything keeps the same name and properties, keeping in mind the difference of syntax between C and Python:


 * https://bitbucket.org/Coin3D/coin/wiki/Documentation - Coin3D API Reference
 * http://www-evasion.imag.fr/~Francois.Faure/doc/inventorMentor/sgi_html/index.html - The Inventor Mentor - The "bible" of Inventor scene description language.

Вы также можете просмотреть в Draft.py файл в папке FreeCAD Mod/Draft, так как там часто используется pivy.

pyCollada

 * homepage: http://pycollada.github.com
 * license: BSD
 * optional, needed to enable import and export of Collada (.DAE) files

pyCollada is a Python library that allow programs to read and write Collada (*.DAE) files. When pyCollada is installed on your system, FreeCAD will be able to handle importing and exporting in the Collada file format.

Installation
Pycollada is usually not yet available in linux distributions repositories, but since it is made only of Python files, it doesn't require compilation, and is easy to install. You have 2 ways, or directly from the official pycollada git repository, or with the easy_install tool.

Linux
In either case, you'll need the following packages already installed on your system:

With easy_install
Assuming you have a complete Python installation already, the easy_install utility should be present already:

You can check if pycollada was correctly installed by issuing in a Python console:

If it returns nothing (no error message), then all is OK

Windows
On Windows since 0.15 pycollada is included in both the FreeCAD release and developer builds so no additional steps are necessary.

MacOS
If you are using the Homebrew build of FreeCAD you can install pycollada into your system Python using pip.

If you need to install pip:

Install pycollada:

If you are using a binary version of FreeCAD, you can tell pip to install pycollada into the site-packages inside FreeCAD.app:

or after downloading the pycollada code

IfcOpenShell

 * homepage: http://www.ifcopenshell.org
 * license: LGPL
 * optional, needed to extend import abilities of IFC files

IFCOpenShell is a library currently in development, that allows to import (and soon export) Industry foundation Classes (*.IFC) files. IFC is an extension to the STEP format, and is becoming the standard in BIM workflows. When ifcopenshell is correctly installed on your system, the FreeCAD Arch Workbench will detect it and use it to import IFC files, instead of its built-in rudimentary importer. Since ifcopenshell is based on OpenCasCade, like FreeCAD, the quality of the import is very high, producing high-quality solid geometry.

Installation
Since ifcopenshell is pretty new, you'll likely need to compile it yourself.

Linux
You will need a couple of development packages installed on your system in order to compile ifcopenshell:

but since FreeCAD requires all of them too, if you can compile FreeCAD, you won't need any extra dependency to compile IfcOpenShell.

Grab the latest source code from here:

The build process is very easy:

or, if you are using oce instead of opencascade:

Since ifcopenshell is made primarily for Blender, it uses Python3 by default. To use it inside FreeCAD, you need to compile it against the same version of Python that is used by FreeCAD. So you might need to force the Python version with additional cmake parameters (adjust the Python version to yours):

Then:

You can check that ifcopenshell was correctly installed by issuing in a Python console:

If it returns nothing (no error message), then all is OK

Windows
Note: Official FreeCAD installers obtained from the FreeCAD website/github page now contain ifcopenshell already.

Copied from the IfcOpenShell README file

Users are advised to use the Visual Studio .sln file in the win/ folder. For Windows users a prebuilt Open CASCADE version is available from the opencascade website. Download and install this version and provide the paths to the Open CASCADE header and library files to MS Visual Studio C++.

For building the IfcPython wrapper, SWIG needs to be installed. Please download the latest swigwin version from swig website. After extracting the .zip file, please add the extracted folder to the PATH environment variable. Python needs to be installed, please provide the include and library paths to Visual Studio.

Links
Tutorial Import/Export IFC - compiling IfcOpenShell

Installation
On all platforms, only by installing the appropriate package from ODA DWG-DXF Converter. After installation, if the utility is not found automatically by FreeCAD, you might need to set the path to the converter executable manually, open Edit → Preferences → Import-Export → DWG and fill "Path to Teigha File Converter" appropriately.

LazyLoader
LazyLoader is a Python module that allows deferred loading, while still importing at the top of the script. This is useful if you are importing another module that is slow, and it is used several times throughout the script. Using LazyLoader can improve workbench startup times, but the module will still need to be loaded on first use.

Installation
LazyLoader is included with FreeCAD v0.19

Usage
You will need to import LazyLoader, then change the import of whatever module you want to be deferred.

The variable Part is how the module is named in your script. You can replicate "import Part as P" by changing the variable.

You can also import a module from a package.

You can't import individual functions, just entire modules.

Links

 * Original source: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/lazy_loader.py
 * Further explanation: https://wil.yegelwel.com/lazily-importing-python-modules/
 * Code within the FreeCAD source code: https://github.com/FreeCAD/FreeCAD/tree/master/src/3rdParty/lazy_loader
 * Forum discussion: https://forum.freecadweb.org/viewtopic.php?f=10&t=45298