Módulos extra de python

From FreeCAD Documentation
Revision as of 12:47, 22 September 2018 by FuzzyBot (talk | contribs) (Updating to match new version of source page)

El interprete de Python dentro de FreeCAD puede extenderse fácilmente añadiendo nuevos módulos a tu instalación de Python. Esos módulos se detectarán automáticamente y utilizarán por FreeCAD.

PySide (previously PyQt4)

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.

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

MacOSX

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

Usage

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

import PySide

To access the FreeCAD interface, type :

from PySide import QtCore,QtGui
FreeCADWindow = 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")

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

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.setWindowModality(QtCore.Qt.ApplicationModal)       # function has been disabled to promote "WindowStaysOnTopHint"
    diag.exec_()

Working with setProperty (PyQt4) and setValue (PySide)

self.doubleSpinBox.setProperty("value", 10.0)  # PyQt4

replace with :

self.doubleSpinBox.setValue(10.0)  # PySide

Working with setToolTip

self.doubleSpinBox.setToolTip(_translate("MainWindow", "Coordinate placement Axis Y", None))  # PyQt4

replace with :

self.doubleSpinBox.setToolTip(_fromUtf8("Coordinate placement Axis Y"))  # PySide

or :

self.doubleSpinBox.setToolTip(u"Coordinate placement Axis Y.")# PySide

Documentación

Más tutoriales de pyQt4 (incluyendo cómo construir interfaces con Qt Designer para utilizar con Python):

http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/classes.html - la referencia oficial del API de PyQt4

http://www.rkblog.rk.edu.pl/w/p/introduction-pyqt4/ - una simple introducción

http://www.zetcode.com/tutorials/pyqt4/ - un tutorial en profundidad muy completo

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

Instalación

Requisitos previos

Creo que antes de compilar Pivy querrás tener Coin y SoQt instalados.

Para construirlo en Mac es suficiente instalar el paquete binario de Coin3. Intentar instalar Coin desde MacPorts es problemático: añadir un montón de paquetes de X Windows y finalmente se cuelga con un error de script.

Para Fedora encontré un RPM con Coin3.

SoQt compilado desde código fuente funciona bien en Mac y Linux.

Debian & Ubuntu

Empezando con Debian Squeeze y Ubuntu Lucid, pivy está disponible directamente desde los repositorios oficiales, ahorrándonos un montón de dificultades. Mientras tanto, puedes descargar uno de los paquetes que hemos creado (para Debian y Ubuntu karmic) disponibles en la página de Descargas, o compilarlo tu mismo.

El mejor modo de compilar pivy siomplemente es aprovechar el paquete de código fuente de Debian para pivy y crear un paquete con debuild. Es el mismo código fuente desde la web oficial de pivy, pero la gente de Debian han creado varios parches adicionales. También se compila bien en Ubuntu karmic: http://packages.debian.org/squeeze/python-pivy, descarga los archivos .orig.gz y .diff.gz, luego descomprimelos, y aplica .diff al código fuente: ve a las carpetas del código fuente descomprimido de pivy, y aplica el parche .diff:

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

luego

debuild

para tener pivy correctamente construido en un paquete oficial de instalación. A continuación, simplemente instala el paquete con gdebi.

Otras distribuciones Linux

Primero consigue la última versión del código fuente de los repositorios del proyecto:

hg clone http://hg.sim.no/Pivy/default Pivy

En marzo de 2012, la última versión es Pivy-0.5

Luego necesitas una herramienta llamada SWIG para generar el código C++ para la vinculación de Python. Pivy-0.5 informa que sólo ha sido comprobado con SWIG 1.3.31, 1.3.33, 1.3.35, y 1.3.40. Así que puedes descargar el código fuente en un tarball para una de dichas versiones anteriores desde http://www.swig.org. Luego descomprimelo y desde la línea de comandos haz lo siguiente (como root):

./configure
make
make install (or checkinstall if you use it)

Esto tardará unos segundos en construirse.

Como alternativa, puedes tratar de construir con un SWIG más reciente. En marzo de 2012, una versión típica del repositorio es la 2.0.4. Pivy tiene un problema menor de compilación con SWIG 2.0.4 en Mac OS (mira más abajo) pero parece construirse bien en Fedora Core 15.

Después de eso ve al archivo que va a los recursos de pivy y ejecuta

python setup.py build

lo que creará los archivos fuente. Ten en cuenta que la construcción puede producir miles de advertencias, pero afortunadamente no hay errores.

Es posible que esto esté obsoleto, pero puedes llegar a un error de compilación donde una constante de tipo caracter (char) no puede ser convertida en una 'char*'. Para solucionarlo sólo necesitas escribir una constante antes de las líneas apropiadas. Hay 6 líneas que corregir.

Después de eso, instalar por publicación (como root):

python setup.py install (or checkinstall python setup.py install)

Eso es todo, pivy está instalado.

Mac OS

Estas instrucciones puede que no estén completas. Algo parecido funciona para OS 10.7 en marzo de 2012. He utilizado MacPorts para los repositorios, pero también deberían funcionar otras opciones.

Para Linux, consigue la última vcersión del código fuente:

hg clone http://hg.sim.no/Pivy/default Pivy

Si no tienes hg, puedes conseguirlo desde MacPorts:

port install mercurial

Luego, como se indica arriba, necesitas SWIG. Debería ser cuestión de hacer:

port install swig

He encontrado que también necesitaba:

port install swig-python

En marzo de 2012, la versión de SWIG en MacPorts es la 2.0.4. Como se ha indicado arriba para Linux, podría ser mejor que descargaras una versión más antigua. SWIG 2.0.4 parece tener un error que detiene la construcción de Pivy. Mira el primer mensaje en este enlace: https://sourceforge.net/mailarchive/message.php?msg_id=28114815

Esto se puede corregir editando las dos ubicaciones de código fuente para añadir: *arg4, *arg5 en lugar de arg4, arg5. Ahora Pivy debería construirse:

python setup.py build
sudo python setup.py install

Windows

Asumiendo que utilizas Visual Studio 2005 o superior deberías abrir una ventana de comandos con 'Visual Studio 2005 Command prompt' desde el menú Herramientas. Si el interprete aún no está en el sistema, haz

set PATH=path_to_python_2.5;%PATH%

Para tener pivy funcionando deberías conseguir las últimas fuentes desde los repositorios del proyect:

svn co https://svn.coin3d.org/repos/Pivy/trunk Pivy

Luego necesitas una herramienta denominada SWIG para generar el ódigo C++ para la vinculación con Python. Es recomendable utilizar la versión 1.3.25 de SWIG, no la última versión, porque de momento pivy sólo funciona correctamente con con la versión with 1.3.25. Descarga los binarios para 1.3.25 desde http://www.swig.org. Luego descomprimelo y desde la línea de comandos añádelo al sistema path

set PATH=path_to_swig_1.3.25;%PATH%

y establece COINDIR a la ruta aproviada

set COINDIR=path_to_coin

En Windows el archivo de configuración de pivyespera SoWin en lugar de SoQt por defecto. No he encontrado una manera obvia para construirlo con SoQt, así que he modificado el arhivo setup.py directamente. En la línea 200 simplemente elimina la parte 'sowin' : ('gui._sowin', 'sowin-config', 'pivy.gui.') (no elimines los paréntesis de cierre).

Después de esto ve a las fuentes de pivy y ejecuta

python setup.py build

lo cual crea los archivos de fuente. Puedes llegar a un error de compilación de 'Varios archivos de cabecera no se han encontrado'. En este caso ajusta la variable INCLUDE

set INCLUDE=%INCLUDE%;path_to_coin_include_dir

y si las cabeceras de SoQt no están en el mismo sitio que las cabeceras de Coin también

set INCLUDE=%INCLUDE%;path_to_soqt_include_dir

y finalmente las cabeceras de Qt

set INCLUDE=%INCLUDE%;path_to_qt4\include\Qt

Si estas utilizando la versión Express Edition de Visual Studio puedes tener una excepción de error de clave de Python. En este caso tendrás que modificar unas cuantas cosas en msvccompiler.py situado en la instalación de Python.

Ve a la línea 122 y reemplaza la línea

vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version

con

vsbase = r"Software\Microsoft\VCExpress\%0.1f" % version

Luego prueba de nuevo. Si te da un segundo error como

error: Python was built with Visual Studio 2003;...

debes reemplazar también la línea 128

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")

con

self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv2.0")

Intenta de nuevo. Si tienes un nuevo error como

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.

entonces deberías comprobar las variables de entorno DISTUTILS_USE_SDK y MSSDK con

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

Ahora, debes encontrar un error de compilación donde una constante de tipo char no se puede convertir en char. Para solucionarlo necesitas escribir una constante antes de las líneas apropiadas. Hay 6 líneas que corregir. Después copia el directorio de pivy generado a un lugar donde el interprete de Python de FreeCAD lo pueda encontrar.

Utilización

To check if Pivy is correctly installed:

import pivy

Para tener Pivy acceso a la escena gráfica de FreeCAD haz lo siguiente:

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

Ahora puedes explorar FCSceneGraph con el comando dir().

Documentación

Desafortunadamente la documentación sobre pivy es casi inexistente en la redt. Pero podrías encontrar la documentación de Coin útil, ya que pivy simplemente traduce las funciones de Coin, los nodos y métodos en Python, todo mantiene el mismo nombre y propiedades, teniendo en cuenta la diferencia de sintaxis entre C y Python:

También puedes echar un vistazo al archivo Draft.py en el directorio de FreeCAD Mod/Draft, ya que hace un uso importante de pivy.

pyCollada

pyCollada es una biblioteca de Python que permite a los programas leer y escribir archivos de Collada (*.DAE). Cuando pyCollada está instalado en tu sistema, FreeCAD (introducido en la versión 0.13) lo detectará y añadirá opciones de importación y exportación para manejar la apertura y guardado en el formato de archivos de Collada.

Instalación

Pycollada no está normalmente disponible en los repositorios de las distribuciones de Linux, pero ya que está creado únicamente por archivos de Python, no es necesaria su compilación, y es sencillo de instalar. Tienes dos métodos, o directamente desde el repositorio ofician en Git de pycollada, o con la herramienta easy_install.

Linux

En ambos casos, necesitaras tener los siguientes paquetes ya instalados en tu sistema:

python-lxml 
python-numpy
python-dateutil
Desde el repositorio de Git
git clone git://github.com/pycollada/pycollada.git pycollada
cd pycollada
sudo python setup.py install
Con easy_install

Asumiendo que ya tienes una instalación completa de Python, la utilidad easy_install ya debería estar presente:

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

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

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

or after downloading the pycollada code

$ export PYTHONPATH=/Applications/FreeCAD\ 0.16.6706.app/Contents/lib/python2.7/site-packages:$PYTHONPATH
$ python setup.py install --prefix=/Applications/FreeCAD\ 0.16.6706.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 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:

git clone https://github.com/IfcOpenShell/IfcOpenShell.git

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 ifcopenshell

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.

Links

Tutorial Import/Export IFC - compiling IfcOpenShell

ODA Converter (previously Teigha Converter)

The ODA 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 https://www.opendesign.com/guestfiles/oda_file_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.

Localisation/es
Source documentation/es