Extra python modules/fr

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

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

Remarque : PyQt4 va devenir progressivement obsolète dans FreeCAD, après la version 0.13, la préférence ira sur PySide, qui fait exactement le même travail, mais dispose d'une licence (LGPL) plus compatible avec 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).

MacOSX
PyQt on Mac can be installed via homebrew or port. See CompileOnMac for more information.

Utilisation
Une fois installé, vous pouvez vérifier le bon fonctionne de l'installation, en tapant dans la console Python de FreeCAD : import PySide Pour accéder à l'interface de FreeCAD, tapez : from PySide import QtCore,QtGui FreeCADWindow = FreeCADGui.getMainWindow Maintenant, vous pouvez commencer l'exploration de l'interface avec la commande dir. Vous pouvez ajouter de nouveaux éléments, comme un widget personnalisé, avec des commandes comme : FreeCADWindow.addDockWidget(QtCore.Qt.RghtDockWidgetArea,my_custom_widget) Working with Unicode : text = text.encode('utf-8') Working with QFileDialog and OpenFileName : path = FreeCAD.ConfigGet("AppHomePath") OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Read a txt file", path, "*.txt") Working with QFileDialog and SaveFileName : path = FreeCAD.ConfigGet("AppHomePath") SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Save a file txt", path, "*.txt")
 * 1) path = FreeCAD.ConfigGet("UserAppData")
 * 1) path = FreeCAD.ConfigGet("UserAppData")

Example of transition from PyQt4 and PySide
PS: these examples of errors were found in the transition PyQt4 to PySide and these corrections were made, other solutions are certainly available with the examples above try: import PyQt4                                       # PyQt4 from PyQt4 import QtGui ,QtCore                    # PyQt4 from PyQt4.QtGui import QComboBox                  # PyQt4 from PyQt4.QtGui import QMessageBox                # PyQt4 from PyQt4.QtGui import QTableWidget, QApplication # PyQt4 from PyQt4.QtGui import *                          # PyQt4 from PyQt4.QtCore import *                         # PyQt4 except Exception: import PySide                                      # PySide from PySide import QtGui ,QtCore                   # PySide from PySide.QtGui import QComboBox                 # PySide from PySide.QtGui import QMessageBox               # PySide from PySide.QtGui import QTableWidget, QApplication # PySide from PySide.QtGui import *                         # PySide from PySide.QtCore import *                        # PySide To access the FreeCAD interface, type : You can add new elements, like a custom widget, with commands like : myNewFreeCADWidget = QtGui.QDockWidget         # create a new dockwidget myNewFreeCADWidget.ui = Ui_MainWindow          # myWidget_Ui             # load the Ui script myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui try: app = QtGui.qApp                             # PyQt4 # the active qt window, = the freecad window since we are inside it    FCmw = app.activeWindow                     # PyQt4 # the active qt window, = the freecad window since we are inside it    FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window except Exception: FCmw = FreeCADGui.getMainWindow            # PySide # the active qt window, = the freecad window since we are inside it     FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window Working with Unicode : try: text = unicode(text, 'ISO-8859-1').encode('UTF-8') # PyQt4 except Exception: text = text.encode('utf-8')                        # PySide Working with QFileDialog and OpenFileName : OpenName = "" try: OpenName = QFileDialog.getOpenFileName(None,QString.fromLocal8Bit("Lire un fichier FCInfo ou txt"),path,"*.FCInfo *.txt") # PyQt4 except Exception: OpenName, Filter = PySide.QtGui.QFileDialog.getOpenFileName(None, "Lire un fichier FCInfo ou txt", path, "*.FCInfo *.txt")#PySide Working with QFileDialog and SaveFileName : SaveName = "" try: SaveName = QFileDialog.getSaveFileName(None,QString.fromLocal8Bit("Sauver un fichier FCInfo"),path,"*.FCInfo") # PyQt4 except Exception: SaveName, Filter = PySide.QtGui.QFileDialog.getSaveFileName(None, "Sauver un fichier FCInfo", path, "*.FCInfo")# PySide The MessageBox: def errorDialog(msg): diag = QtGui.QMessageBox(QtGui.QMessageBox.Critical,u"Error Message",msg ) try: diag.setWindowFlags(PyQt4.QtCore.Qt.WindowStaysOnTopHint) # PyQt4 # this function sets the window before except Exception: diag.setWindowFlags(PySide.QtCore.Qt.WindowStaysOnTopHint)# PySide # this function sets the window before diag.exec_ Working with setProperty (PyQt4) and setValue (PySide) self.doubleSpinBox.setProperty("value", 10.0) # PyQt4 replace to : self.doubleSpinBox.setValue(10.0) # PySide Working with setToolTip self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None)) # PyQt4 replace to : self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y")) # PySide or : self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide
 * 1)    diag.setWindowModality(QtCore.Qt.ApplicationModal)       # function has been disabled to promote "WindowStaysOnTopHint"

Documentation
Plus de tutoriels sur PyQt4 (y compris sur la façon de construire des interfaces avec Qt Designer pour utiliser avec python) :

API PyQt4 - La référence officielle sur l'API de PyQt4

Introduction PyQt4- une simple introduction.

un tutoriel - vraiment complet.

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 MacOSX, unfortunately, you will need to compile pivy yourself.

Prérequis
Je crois, qu'avant de compiler Pivy vous devez avoir Coin et SoQt d'installés.

J'ai trouvé que pour la compilation sur Mac, il suffisait d'installer le Coin3 binary package.

La tentative d'installation de Coin sur MacPorts était problématique : j'ai essayé d'ajouter un grand nombre de paquets X Windows, et, finalement, tout c'est terminé avec une erreur de script !

Pour Fedora, j'ai trouvé un RPM avec Coin3.

SoQt, compilé à partir des sources fonctionne très bien sur Mac et Linux.

Debian & Ubuntu
Depuis Debian Squeeze et Ubuntu Lucid, Pivy est disponible directement à partir des dépôts officiels, et, nous permet d'économiser beaucoup de tracas.

En attendant, vous pouvez soit télécharger l'un des packages que nous avons fait (pour Debian et Ubuntu karmic), disponibles sur les pages de téléchargements, ou, vous pouvez le compiler vous-même.

La meilleure façon de compiler facilement Pivy, est de prendre le debian source package pour Pivy, et, faire un package avec debuild.

C'est le même code source que sur le site officiel de Pivy, mais, les gens de Debian ont ajoutés plusieurs bug-fixing. Il compile également très bien sur : Ubuntu Karmic ... télécharger .orig.gz et .diff.gz, décompressez le tout, puis appliquez .diff à la source :

allez dans le dossier source de Pivy décompressé, et appliquez le patch .diff : patch -p1 < ../pivy_0.5.0~svn765-2.diff alors debuild pour avoir Pivy, correctement compilé, avec un package officiellement installable. Ensuite, il suffit d'installer le package avec gdebi.

Autres distributions Linux
D'abord, téléchargez les dernières sources du project's repository : hg clone http://hg.sim.no/Pivy/default Pivy En Mars 2012, la dernière version était la pivy-0.5.

Ensuite, vous avez besoin d'un outil appelé SWIG pour générer le code C++ pour les Python bindings. Pivy-0.5 rapports qui a été testé seulement avec SWIG 1.3.31, 1.3.33, 1.3.35 et 1.3.40. Ainsi, vous pouvez télécharger une archive source pour l'une de ces anciennes versions de SWIG.

Puis, décompressez-le, et, faites en ligne de commande (en tant que root) : ./configure make make install (or checkinstall if you use it) Il faut quelques secondes pour la compilation.

Alternativement, vous pouvez essayer avec une compilation plus récent SWIG. En Mars 2012, la version référentielle typique était 2.0.4.

Pivy a un problème de compilation avec les versions inférieures 2.0.4 de SWIG sur Mac OS (voir ci-dessous), mais semble compiler correctement sur Fedora Core 15.

Après cela, allez dans le source Pivy et tapez : python setup.py build pour créer les fichiers sources. Notez que cette génération de fichiers peut produire des milliers de mises en garde, mais j'espère qu'il n'y aura pas d'erreurs.

Ceci est probablement obsolète, mais vous risquez de rencontrer une erreur de compilation, ou, un "const char*" ne peut pas être converti en un "char*".

Pour corriger cela, il vous suffit d'écrire une "const", dans les lignes appropriées, avant la génération. Il y a six lignes à corriger.

Après cela, installez (en tant que root) : python setup.py install (or checkinstall python setup.py install) Ça y est, pivy est installé.

Mac OS
Ces instructions peuvent ne pas être complètes. Quelque chose plus ou moins comme cela a fonctionné pour OS 10.7 de Mars 2012. J'utilise MacPorts pour les dépôts, mais d'autres options devraient également fonctionner.

En ce qui concerne linux, téléchargez les dernières sources : hg clone http://hg.sim.no/Pivy/default Pivy Si vous n'avez pas hg, vous pouvez l'obtenir à partir MacPorts : port install mercurial Puis, comme ci-dessus vous avez besoin SWIG.

Faites : port install swig J'ai trouvé que j'avais besoin aussi de faire : port install swig-python En Mars 2012, MacPorts SWIG est la version 2.0.4. Comme il est indiqué ci-dessus pour Linux, il vaudrait mieux télécharger une version plus ancienne. SWIG 2.0.4 semble avoir un bug qui empêche la compilation de Pivy.

Regardez le premier message dans ce : digest

Cela peut être corrigé, en modifiant les 2 emplacements source et déréférencer : *arg4, *arg5 à la place de arg4, arg5.

Maintenant nous pouvons compiler Pivy: python setup.py build sudo python setup.py install

Windows
En supposant que vous utilisiez Visual Studio 2005 ou une version ultérieure, vous devrez ouvrir une invite de commande avec Visual Studio 2005 Command prompt dans le menu Outils.

Si l'interpréteur Python n'est pas encore dans le chemin système (PATH), faites : set PATH=path_to_python_2.5;%PATH% Pour que Pivy soit fonctionnel, vous devriez télécharger les dernières sources à partir du référentiel du projet : svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy Ensuite, vous avez besoin d'un outil appelé SWIG pour générer le code C++ pour les Python bindings. Il est recommandé d'utiliser la version 1.3.25 de SWIG, pas la dernière version, parceque, Pivy ne fonctionne pas correctement avec la version 1.3.25. Télécharger le binaire pour la version 1.3.25 de Swig.

Puis décompressez-le et à partir de la ligne de commande, ajoutez le chemin (path) du système set PATH=path_to_swig_1.3.25;%PATH% et définir le chemin approprié à COINDIR : set COINDIR=path_to_coin Sous Windows, le fichier de configuration Pivy attend SoWin au lieu de SoQt par défaut. Je n'ai pas trouvé de façon évidente pour compiler avec SoQt, alors, j'ai modifié le fichier setup.py directement.

A la ligne 200 il suffit de retirer la partie sowin : ('gui._sowin', 'sowin-config', 'pivy.gui.') (ne pas enlever la parenthèse fermante ! ).

Après cela, allez dans le source de pivy et tapez : python setup.py build qui crée les fichiers source. Vous pouvez rencontrer une erreur de compilation, cause, plusieurs fichiers d'en-tête n'ont pas été trouvés.

Dans ce cas, réglez la variable INCLUDE comme ceci : set INCLUDE=%INCLUDE%;path_to_coin_include_dir et si les en-têtes soqt, ne sont pas au même endroit que les en-têtes Coin, faites aussi ceci : set INCLUDE=%INCLUDE%;path_to_soqt_include_dir et finalement, pour les en-têtes Qt faites : set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt If you are using the Express Edition of Visual Studio you may get a python keyerror exception. In this case you have to modify a few things in msvccompiler.py located in your python installation.

Go to line 122 and replace the line vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version with vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version Then retry again. If you get a second error like error: Python was built with Visual Studio 2003;... you must also replace line 128 self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") with self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0") Retry once again. If you get again an error like error: Python was built with Visual Studio version 8.0, and extensions need to be built with the same version of the compiler, but it isn't installed. then you should check the environment variables DISTUTILS_USE_SDK and MSSDK with echo %DISTUTILS_USE_SDK% echo %MSSDK% If not yet set then just set it e.g. to 1 set DISTUTILS_USE_SDK=1 set MSSDK=1 Now, 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 copy the generated pivy directory to a place where the python interpreter in FreeCAD can find it.

Usage
To check if Pivy is correctly installed: import pivy To have Pivy access the FreeCAD scenegraph do the following: from pivy import coin App.newDocument # Open a document and a view view = Gui.ActiveDocument.ActiveView FCSceneGraph = view.getSceneGraph # returns a pivy Python object that holds a SoSeparator, the main "container" of the Coin scenegraph FCSceneGraph.addChild(coin.SoCube) # add a box to scene You can now explore the FCSceneGraph with the dir command.

Additonal Documentation
Unfortunately documentation about pivy is still almost inexistant 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.

You can also look at the Draft.py file in the FreeCAD Mod/Draft folder, since it makes big use of 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: python-lxml python-numpy python-dateutil

From the git repository
git clone git://github.com/pycollada/pycollada.git pycollada cd pycollada sudo python setup.py install

With easy_install
Assuming you have a complete python installation already, the easy_install utility should be present already: easy_install pycollada You can check if pycollada was correctly installed by issuing in a python console: import collada If it returns nothing (no error message), then all is OK

Windows

 * 1) Install Python. While FreeCAD and some other programs come with a bundled version of Python, having a fixed install will help with the next steps. You can get Python here: https://www.python.org/downloads/ . Of course you should pick the right version, in this case that would be 2.6.X, as FreeCAD currently uses 2.6.2 (Personally I went with 2.6.2, and by the way, you can check the version yourself by starting the Python.exe in the bin folder of FreeCAD). You'll also have to add the path of the installation directory into the path variable so you can access Python from the cmd. Now we can install the missing things, in total there are 3 things we need to install: numpy, setuptools, pycollada
 * 2) Fetch numpy here: http://sourceforge.net/projects/numpy/files/NumPy/ . Pick a version which fits to the version used by FreeCAD, there are multiple installers for different Python versions in every numpy version folder, the installer will put numpy into the folder of your Python installation, where FreeCAD can access it as well
 * 3) Fetch setuptools here: https://pypi.python.org/pypi/setuptools (We need to install the setuptools in order to install pycollada in the next step)
 * 4) Unzip the downloaded setuptools  file somewhere
 * 5) Start a cmd with admin permission
 * 6) Navigate to the unpacked setuptools folder
 * 7) Install the setuptools by tipping "Python setup.py install" into the cmd, this will not work when Python is not installed or when the path variable hasn't been configured
 * 8) Fetch pycollada here: https://pypi.python.org/pypi/pycollada/ (has already been posted above) and once again:
 * 9) Unzip the downloaded pycollada file somewhere
 * 10) Start a cmd with admin permission, or use the one you opened not long ago
 * 11) Navigate to the unpacked pycollada folder
 * 12) Install the setuptools by tipping "Python setup.py install" into the cmd


 * Another reference on how to use easy_install: http://jishus.org/?p=452

Mac OS
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: $ sudo easy_install pip Install pycollada: $ sudo 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: $ pip install --target="/Applications/FreeCAD.app/Contents/lib/python2.7/site-packages" pycollada

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 Module 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: liboce-*-dev python-dev swig 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: svn co https://ifcopenshell.svn.sourceforge.net/svnroot/ifcopenshell ifcopenshell The build process is very easy: mkdir ifcopenshell-build cd ifcopenshell-build cmake ../ifcopenshell/cmake or, if you are using oce instead of opencascade: cmake -DOCC_INCLUDE_DIR=/usr/include/oce ../ifcopenshell/cmake 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): cmake -DOCC_INCLUDE_DIR=/usr/include/oce -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/python2.7.so ../ifcopenshell/cmake Then: make sudo make install You can check that ifcopenshell was correctly installed by issuing in a python console: import IfcImport If it returns nothing (no error message), then all is OK

Windows
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 http://opencascade.org 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 http://www.swig.org/download.html. 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.

Teigha Converter

 * homepage: http://www.opendesign.com/guestfiles/TeighaFileConverter
 * license: freeware
 * optional, used to enable import and export of DWG files

The Teigha Converter is a small freely available utility that allows to convert between several versions of DWG and DXF files. FreeCAD can use it to offer DWG import and export, by converting DWG files to the DXF format under the hood,then using its standard DXF importer to import the file contents. The restrictions of the DXF importer apply.

Installation
On all platforms, only by installing the appropriate package from http://www.opendesign.com/guestfiles/TeighaFileConverter. After installation, if the utility is not found automatically by FreeCAD, you might need to set the path to the converter executable manually, in the menu Edit -> Preferences -> Draft -> Import/Export options.