Extra python modules

From FreeCAD Documentation
This page is a translated version of the page Extra python modules and the translation is 1% complete.
Outdated translations are marked like this.

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

PySide 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, BIM, etc) are enabled after FreeCAD is installed, it means PySide 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.

Installation

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:

importPySide

To access the FreeCAD interface, type:

fromPySideimportQtCore,QtGuiFreeCADWindow=FreeCADGui.getMainWindow()

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

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")#path = FreeCAD.ConfigGet("UserAppData")OpenName,Filter=PySide.QtGui.QFileDialog.getOpenFileName(None,"Read a txt file",path,"*.txt")

Working with QFileDialog and SaveFileName:

path=FreeCAD.ConfigGet("AppHomePath")#path = FreeCAD.ConfigGet("UserAppData")SaveName,Filter=PySide.QtGui.QFileDialog.getSaveFileName(None,"Save a file txt",path,"*.txt")

Additional documentation

Pivy

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.

Installation

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

Starting with Debian Squeeze and Ubuntu Lucid, pivy will be available directly from the official repositories, saving us a lot of hassle. In the meantime, you can either download one of the packages we made (for debian and ubuntu karmic) availables on the Download pages, or compile it yourself.

The best way to compile pivy easily is to grab the debian source package for pivy and make a package with debuild. It is the same source code from the official pivy site, but the debian people made several bug-fixing additions. It also compiles fine on ubuntu karmic: http://packages.debian.org/squeeze/python-pivy download the .orig.gz and the .diff.gz file, then unzip both, then apply the .diff to the source: go to the unzipped pivy source folder, and apply the .diff patch:

patch-p1<../pivy_0.5.0~svn765-2.diff

then

debuild

to have pivy properly built into an official installable package. Then, just install the package with gdebi.

Other Linux distributions

First get the latest sources from the project's repository:

Information to be added.

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

Then you need a tool called SWIG to generate the C++ code for the Python bindings. Pivy-0.5 reports that it has only been tested with SWIG 1.3.31, 1.3.33, 1.3.35, and 1.3.40. So you can download a source tarball for one of these old versions from http://www.swig.org. Then unpack it and from a command line do (as root):

./configuremakemakeinstall(orcheckinstallifyouuseit)

It takes just a few seconds to build.

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

pythonsetup.pybuild

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

pythonsetup.pyinstall(orcheckinstallpythonsetup.pyinstall)

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:

hgclonehttp://hg.sim.no/Pivy/defaultPivy

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

portinstallmercurial

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

portinstallswig

I found I needed also:

portinstallswig-python

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:

pythonsetup.pybuildsudopythonsetup.pyinstall

Windows

Assuming you are using Visual Studio 2005 or later you should open a command prompt with 'Visual Studio 2005 Command prompt' from the Tools menu. If the Python interpreter is not yet in the system path do

setPATH=path_to_python_3.x;%PATH%

To get pivy working you should get the latest sources from the project's repository:

Information to be added.

Then you need a tool called SWIG to generate the C++ code for the Python bindings. It is recommended to use version 1.3.25 of SWIG, not the latest version, because at the moment pivy will only function correctly with 1.3.25. Download the binaries for 1.3.25 from http://www.swig.org. Then unpack it and from the command line add it to the system path

setPATH=path_to_swig_1.3.25;%PATH%

and set COINDIR to the appropriate path

setCOINDIR=path_to_coin

On Windows the pivy config file expects SoWin instead of SoQt as default. I didn't find an obvious way to build with SoQt, so I modified the file setup.py directly. In line 200 just remove the part 'sowin': ('gui._sowin', 'sowin-config', 'pivy.gui.') (do not remove the closing parenthesis).

After that go to the pivy sources and call

pythonsetup.pybuild

which creates the source files. You may run into a compiler error several header files couldn't be found. In this case adjust the INCLUDE variable

setINCLUDE=%INCLUDE%;path_to_coin_include_dir

and if the SoQt headers are not in the same place as the Coin headers also

setINCLUDE=%INCLUDE%;path_to_soqt_include_dir

and finally the Qt headers

setINCLUDE=%INCLUDE%;path_to_pyside\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:PythonwasbuiltwithVisualStudio2003;...

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:PythonwasbuiltwithVisualStudioversion8.0,andextensionsneedtobebuiltwiththesameversionofthecompiler,butitisn'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

setDISTUTILS_USE_SDK=1setMSSDK=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:

importpivy

To have Pivy access the FreeCAD scenegraph do the following:

frompivyimportcoinApp.newDocument()# Open a document and a viewview=Gui.ActiveDocument.ActiveViewFCSceneGraph=view.getSceneGraph()# returns a pivy Python object that holds a SoSeparator, the main "container" of the Coin scenegraphFCSceneGraph.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 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:

You can also look at the Draft.py file in the FreeCAD Mod/Draft folder, since it makes big use of pivy.

pyCollada

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

Linux

sudoapt-getinstallpython3-collada

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

importcollada

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

Linux AppImages and Snaps

Paste this code in the Python console:

importaddonmanager_utilitiesasutilsimportsubprocessimportosifhasattr(utils,"get_python_exe"):# For v0.21:python_exe=utils.get_python_exe()else:# For v0.22/v1.0:fromfreecad.utilsimportget_python_exepython_exe=get_python_exe()vendor_path=utils.get_pip_target_directory()ifnotos.path.exists(vendor_path):os.makedirs(vendor_path)subprocess.run([python_exe,"-m","pip","install","--disable-pip-version-check","--target",vendor_path,"pycollada",],stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=120,check=True,)

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:

$sudoeasy_installpip

Install pycollada:

$sudopipinstallpycollada

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

$pipinstall--target="/Applications/FreeCAD.app/Contents/lib/python3.x/site-packages"pycollada

or after downloading the pycollada code

$exportPYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python3.x/site-packages:$PYTHONPATH$pythonsetup.pyinstall--prefix=/Applications/FreeCAD\ 0.2x.yyyy.app/Contents

IfcOpenShell

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

Linux

Installation instructions can be found here.

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

importifcopenshell

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

Windows and macOS

IfcOpenShell is included in both the FreeCAD release and developer builds so no additional steps are necessary.

Links

Tutorial Import/Export IFC - compiling IfcOpenShell

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.

fromlazy_loader.lazy_loaderimportLazyLoaderPart=LazyLoader('Part',globals(),'Part')

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

P=LazyLoader('Part',globals(),'Part')

You can also import a module from a package.

utils=LazyLoader('PathScripts',globals(),'PathScripts.PathUtils')

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

Links


Localisation/cs
Source documentation/cs