Code snippets/fr: Difference between revisions

From FreeCAD Documentation
(Updating to match new version of source page)
Line 1: Line 1:
This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...
= Code_snippets/fr =
__TOC__


Cette page contient, des exemples, des extraits de code en Python FreeCAD, recueillis auprès d'utilisateurs expérimentés et de produits de discussions sur les [http://forum.freecadweb.org/ forums].<br>
Lisez les et utilisez les comme point de départ pour vos propres scripts . . .

=== Un fichier typique InitGui.py ===

En plus de votre module principal, chaque module doit contenir, un fichier '''InitGui.py''', responsable de l'insertion du module dans l'interface principale.<br>
Ceci est un simple exemple.


=== A typical InitGui.py file ===
Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.
<syntaxhighlight>
class ScriptWorkbench (Workbench):
class ScriptWorkbench (Workbench):
MenuText = "Scripts"
MenuText = "Scripts"
Line 18: Line 13:
Gui.addWorkbench(ScriptWorkbench())
Gui.addWorkbench(ScriptWorkbench())
</syntaxhighlight>


=== Un fichier module typique ===
=== A typical module file ===
This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.

<syntaxhighlight>
Ceci est l'exemple d'un fichier module principal, il contient tout ce que fait votre module. C'est le fichier '''Scripts.py''' invoqué dans l'exemple précédent.<br>
Vous avez ici toutes vos commandes personnalisées.

import FreeCAD, FreeCADGui
import FreeCAD, FreeCADGui
Line 34: Line 28:
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())
</syntaxhighlight>


=== Importer un nouveau type de fichier ===
=== Import a new filetype ===
Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:
Importer un nouveau type de fichier dans FreeCAD est facile.
FreeCAD ne prends pas en considération l'importation de n'importe quelle données dans un document ouvert, parce que, vous ne pouvez pas ouvrir directement un nouveau type de fichier.<br>
Donc, ce que vous devez faire, c'est ajouter la nouvelle extension de fichier à la liste des extensions connues de FreeCAD, et, d'écrire le code qui va lire le fichier et créer les objets FreeCAD que vous voulez.<br>
Cette ligne doit être ajoutée au fichier '''InitGui.py''' pour ajouter la nouvelle extension de fichier à la liste:


This line must be added to the InitGui.py file to add the new file extension to the list:
<syntaxhighlight>
# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")
FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")
</syntaxhighlight>

Puis, dans le fichier '''Import_Ext.py''', faites:
Then in the Import_Ext.py file:
<syntaxhighlight>

def open(filename):
def open(filename):
doc=App.newDocument()
doc=App.newDocument()
# here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
# here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
doc.recompute()
doc.recompute()
</syntaxhighlight>

To export your document to some new filetype works the same way, except that you use:
Pour '''exporter''' votre document avec une nouvelle extension, le fonctionnement est le même,<br>
mais vous devrez faire:

FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")
FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")


=== Ajouter une ligne ===
=== Adding a line ===
A line simply has 2 points.

<syntaxhighlight>
Une ligne, à uniquement deux points.


import Part,PartGui
import Part,PartGui
Line 68: Line 60:
doc.addObject("Part::Feature","Line").Shape=l.toShape()
doc.addObject("Part::Feature","Line").Shape=l.toShape()
doc.recompute()
doc.recompute()
</syntaxhighlight>


=== Ajouter un polygone ===
=== Adding a polygon ===
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

<syntaxhighlight>
Un polygone est simplement un ensemble de segments connnectés (un polyline dans AutoCAD) il n'est pas obligatoirement fermé.

import Part,PartGui
import Part,PartGui
doc=App.activeDocument()
doc=App.activeDocument()
Line 86: Line 78:
p.Nodes=n
p.Nodes=n
doc.recompute()
doc.recompute()
</syntaxhighlight>


=== Ajout et suppression d'objet(s) dans un groupe ===
=== Adding and removing an object to a group ===
<syntaxhighlight>

doc=App.activeDocument()
doc=App.activeDocument()
grp=doc.addObject("App::DocumentObjectGroup", "Group")
grp=doc.addObject("App::DocumentObjectGroup", "Group")
Line 94: Line 87:
grp.addObject(lin) # adds the lin object to the group grp
grp.addObject(lin) # adds the lin object to the group grp
grp.removeObject(lin) # removes the lin object from the group grp
grp.removeObject(lin) # removes the lin object from the group grp
</syntaxhighlight>
Note: You can even add other groups to a group...


=== Adding a Mesh ===
'''PS:''' vous pouvez aussi ajouter un groupe dans un groupe . . .
<syntaxhighlight>

=== Ajout d'une maille (Mesh) ===

import Mesh
import Mesh
doc=App.activeDocument()
doc=App.activeDocument()
Line 121: Line 114:
me=doc.addObject("Mesh::Feature","Cube")
me=doc.addObject("Mesh::Feature","Cube")
me.Mesh=m
me.Mesh=m
</syntaxhighlight>


=== Ajout d'un arc ou d'un cercle ===
=== Adding an arc or a circle ===
<syntaxhighlight>

import Part
import Part
doc = App.activeDocument()
doc = App.activeDocument()
Line 131: Line 125:
f.Shape = c.toShape() # Assign the circle shape to the shape property
f.Shape = c.toShape() # Assign the circle shape to the shape property
doc.recompute()
doc.recompute()
</syntaxhighlight>


=== Accessing and changing representation of an object ===
=== Accéder et changer la représentation d'un objet ===
Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...

<syntaxhighlight>
Chaque objet dans un document FreeCAD a un objet '''vue''' associé a une '''représentation''' qui stocke tous les paramètres qui définissent les propriétés de l'objet, comme, la couleur, l'épaisseur de la ligne, etc ..

gad=Gui.activeDocument() # access the active document containing all
gad=Gui.activeDocument() # access the active document containing all
# view representations of the features in the
# view representations of the features in the
# corresponding App document
# corresponding App document
v=gad.getObject("Cube") # access the view representation to the Mesh feature 'Cube'
v=gad.getObject("Cube") # access the view representation to the Mesh feature 'Cube'
v.ShapeColor # prints the color to the console
v.ShapeColor # prints the color to the console
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
</syntaxhighlight>


=== Observation des évènements de la souris dans la vue 3D via Python ===
=== Observing mouse events in the 3D viewer via Python ===
The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.

<syntaxhighlight>
Le cadre '''Inventor''' permet d'ajouter un ou plusieurs noeuds (nodes) de rappel à la scène graphique visualisée.<br>
Par défaut, FreeCAD, possède un noeud (node) de rappel installé par la visionneuse (fenêtre d'affichage des graphes), qui permet d'ajouter des fonctions statiques ou globales en C++.<br>
Des méthodes de liaisons appropriées sont fournies avec Python, pour permettre l'utilisation de cette technique à partir de codes Python.

App.newDocument()
App.newDocument()
v=Gui.activeDocument().activeView()
v=Gui.activeDocument().activeView()
Line 164: Line 156:
o = ViewObserver()
o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
</syntaxhighlight>

Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call
Maintenant, choisissez une zone dans l'écran (surface de travail) 3D et observez les messages affichés dans la fenêtre de sortie.<br>
<syntaxhighlight>
Pour terminer l'observation il suffit de faire:

v.removeEventCallback("SoMouseButtonEvent",c)
v.removeEventCallback("SoMouseButtonEvent",c)
</syntaxhighlight>
The following event types are supported
* SoEvent -- all kind of events
* SoButtonEvent -- all mouse button and key events
* SoLocation2Event -- 2D movement events (normally mouse movements)
* SoMotion3Event -- 3D movement events (normally spaceball)
* SoKeyboardEvent -- key down and up events
* SoMouseButtonEvent -- mouse button down and up events
* SoSpaceballButtonEvent -- spaceball button down and up events


The Python function that can be registered with addEventCallback() expects a dictionary. Depending on the watched event the dictionary can contain different keys.
Les types d’évènements suivants sont pris en charge:<br>
* '''SoEvent''' -- tous types d'évènements
* '''SoButtonEvent''' -- tous les évènements, boutons, molette
* '''SoLocation2Event''' -- tous les évènements 2D (déplacements normaux de la souris)
* '''SoMotion3Event''' -- tous les évènements 3D (pour le spaceball)
* '''SoKeyboardEvent''' -- évènements des touches {{KEY|flèche haut}} et {{KEY|flèche bas}}
* '''SoMouseButtonEvent''' -- tous les évènements boutons Haut et Bas de la souris
* '''SoSpaceballButtonEvent''' -- tous les évènements Haut et Bas (pour le spaceball)<br><br>
Les fonctions Python qui peuvent être enregistrées avec '''addEventCallback()''' attendent la définition d'une bibliothèque.<br>
Suivant la façon dont l’évènement survient, la bibliothèque peut disposer de différentes clefs.<br>
Il y a une clef pour chaque événement:<br><br>
* '''Type''' -- le nom du type d'évènement par exemple '''SoMouseEvent, SoLocation2Event, ...'''
* '''Time''' -- l'heure courante codée dans une chaîne '''string'''
* '''Position''' -- un tuple de deux '''[http://docs.python.org/library/functions.html#int integers]''', donant la position x,y de la souris
* '''ShiftDown''' -- type boolean, '''true''' si {{KEY|Shift}} est pressé sinon, '''false'''
* '''CtrlDown''' -- type boolean, '''true''' si {{KEY|Ctrl}} est pressé sinon, '''false'''
* '''AltDown''' -- type boolean, '''true''' si {{KEY|Alt}} est pressé sinon, '''false''' <br><br>
For all events it has the keys:
Pour un évènement bouton comme clavier, souris ou spaceball<br>
* Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ...
* '''State''' -- la chaîne '''UP''' si le bouton est relevé, '''DOWN''' si le bouton est enfoncé ou '''UNKNOWN''' si rien ne se passe
* Time -- the current time as string
* Position -- a tuple of two integers, mouse position
* ShiftDown -- a boolean, true if Shift was pressed otherwise false
* CtrlDown -- a boolean, true if Ctrl was pressed otherwise false
* AltDown -- a boolean, true if Alt was pressed otherwise false
For all button events, i.e. keyboard, mouse or spaceball events
Pour un évènement clavier:
* State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases
* '''Key''' -- le caractère de la touche qui est pressée
For keyboard events:
Pour un évènement bouton de souris:
* Key -- a character of the pressed key
* '''Button''' -- le bouton pressé peut être BUTTON1, ..., BUTTON5 ou tous
For mouse button event
Pour un évènement spaceball:
* '''Button''' -- le bouton pressé peut être BUTTON1, ..., BUTTON7 ou tous <br>
* Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY
For spaceball events:
Et finalement les évènement de mouvements:<br>
* Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY
* '''Translation''' -- un tuple de trois '''[http://docs.python.org/library/functions.html#float float()]'''
* '''Rotation''' -- un quaternion, tuple de quattre '''[http://docs.python.org/library/functions.html#float float()]'''
And finally motion events:

* Translation -- a tuple of three floats
=== Manipulation de scènes graphiques en Python ===
* Rotation -- a quaternion for the rotation, i.e. a tuple of four floats

Il est aussi possible d'afficher ou de changer de scène en programmation Python, avec le module '''[[pivy/fr|pivy]]''' en combinaison avec [http://www.coin3d.org/ Coin]


=== Manipulate the scenegraph in Python ===
It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.
<syntaxhighlight>
from pivy.coin import * # load the pivy module
from pivy.coin import * # load the pivy module
view = Gui.ActiveDocument.ActiveView # get the active viewer
view = Gui.ActiveDocument.ActiveView # get the active viewer
Line 213: Line 204:
root.addChild(SoCube())
root.addChild(SoCube())
view.fitAll()
view.fitAll()
</syntaxhighlight>

L'API Python de pivy est créé en utilisant l'outil [http://www.swig.org/ SWIG]. Comme dans FreeCAD nous utilisons certains noeuds (nodes) écrits automatiquement nous ne pouvons pas les créer directement en Python.<br>
The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python.
However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with
Il est cependant, possible de créer un noeud avec son nom interne.<br>
<syntaxhighlight>
Un exemple de '''SoFCSelection''', le '''type''' peut être créé avec:

type = SoType.fromName("SoFCSelection")
type = SoType.fromName("SoFCSelection")
node = type.createInstance()
node = type.createInstance()
</syntaxhighlight>


=== Ajouter et effacer des objets de la scène ===
=== Adding and removing objects to/from the scenegraph ===
Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):

<syntaxhighlight>
Ajouter de nouveaux noeuds dans la scène graphique peut être fait de cette façon. Prenez toujours soin d'ajouter un '''SoSeparator''' pour, contenir les propriétés de la forme géométrique, les coordonnées et le matériel d'un même objet.<br>
L'exemple suivant ajoute une ligne rouge à partir de (0,0,0) à (10,0,0):

from pivy import coin
from pivy import coin
sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
Line 240: Line 229:
no.addChild(li)
no.addChild(li)
sg.addChild(no)
sg.addChild(no)
</syntaxhighlight>

To remove it, simply issue:
Pour le supprimer, il suffit de:
<syntaxhighlight>

sg.removeChild(no)
sg.removeChild(no)
</syntaxhighlight>


===Ajout de widgets personnalisés à l'interface===
===Adding custom widgets to the interface===
You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PyQt4.

Vous pouvez créer un widget avec [http://fr.wikipedia.org/wiki/Qt Qt designer], le transformer en Script Python et l'incorporer dans l'interface de FreeCAD avec [[PyQt/fr|PyQt4]].<br>
généralement codé comme ceci (il est simple, vous pouvez aussi le coder directement en Python):


The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):
<syntaxhighlight>
class myWidget_Ui(object):
class myWidget_Ui(object):
def setupUi(self, myWidget):
def setupUi(self, myWidget):
Line 262: Line 252:
myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))
</syntaxhighlight>

Puis, vous devez créer une référence à la fenêtre FreeCAD Qt, lui insérer le widget personnalisé, et transférer le code Ui du widget que nous venons de faire dans le vôtre avec:
Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:
<syntaxhighlight>

app = QtGui.qApp
app = QtGui.qApp
FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
Line 271: Line 261:
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
</syntaxhighlight>


===Adding a Tab to the Combo View===
*Ici, le code Python est généré par le compilateur '''Ui Python''' avec le module '''pyuic.py''' (il existe aussi pyuic4.py attention à la compatibilité).<br>
The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.
**Vous pouvez trouver ce fichier à l'emplacement '''"C:\Program Files\FreeCAD0.13\bin\PyQt4\uic"''',
<syntaxhighlight>
* '''pyuic.py''' est l'outil qui convertit les fichiers qt-designer '''.ui''' (Interface Utilisateur) en fichier '''.py''' (code Python), la ligne de commande dans la console DOS est '''"pyuic -x fichier.ui > fichier.py"'''<br>
* vous pouvez créer un fichier .bat pour automatiser la commande:
* (avec Python27) copier cette ligne dans un fichier texte, et, le sauver le sous le nom '''"compile.bat"'''

@"C:\Python27\python" "C:\Python27\Lib\site-packages\PyQt4\uic\pyuic.py" -x %1.ui > %1.py

(au besoin, adaptez le chemin à votre version de Python)

Si vous utilisez les outils fourni dans FreeCAD, le code sera,

@"C:\Program Files\FreeCAD0.13\bin\python" "C:\Program Files\FreeCAD0.13\bin\PyQt4\uic\pyuic.py" -x %1.ui > %1.py

* et tapez à la ligne de commande " '''compile fichier''' " sans extension, le nom "'''fichier'''" entré '''.ui''', sera le nom sortant avec extension '''.py'''
* '''ATTENTION: il faut que les fichiers soient présents, et, accessibles, vérifiez que les fichiers sont présents et que les chemins sont justes !'''
* pour cet exemple entièrement automatique et simplifié, '''"compile.bat"''' est au même endroit que le '''fichier.ui''' à convertir en '''fichier.py'''<br><br>
Autres liens de documentation [http://www.qtrac.eu/pyqtbook.html "Python and Qt"] , sur [http://ogirardot.developpez.com/introduction-pyqt/ Développez.com] et bien d'autres.

Vous pouvez installer une version complète de Python qui comprend [http://www.riverbankcomputing.co.uk/software/pyqt/download '''PyQt, Qt Designer ...''']

===Ajout d'une liste déroulante===

Le code suivant vous permet d'ajouter une liste déroulante dans FreeCAD, en plus des onglets "Projet" et "tâches".<br>
Il utilise également le module '''uic''' pour charger un fichier '''ui''' directement dans cet onglet.

from PyQt4 import QtGui,QtCore
from PyQt4 import QtGui,QtCore
from PyQt4 import uic
from PyQt4 import uic
Line 328: Line 296:
#tab.removeTab(2)
#tab.removeTab(2)
</syntaxhighlight>


===Ouverture d'une page web===
===Opening a custom webpage===
<syntaxhighlight>

import WebGui
import WebGui
WebGui.openBrowser("http://www.example.com")
WebGui.openBrowser("http://www.example.com")
</syntaxhighlight>


===Obtenir le code HTML d'une page Web ouverte===
===Getting the HTML contents of an opened webpage===
<syntaxhighlight>

from PyQt4 import QtGui,QtWebKit
from PyQt4 import QtGui,QtWebKit
a = QtGui.qApp
a = QtGui.qApp
Line 342: Line 312:
html = unicode(v.toHtml())
html = unicode(v.toHtml())
print html
print html
</syntaxhighlight>


===Extraire et utiliser les coordonnées de 3 points sélectionnés===
===Retrieve and use the coordinates of 3 selected points or objects===
<syntaxhighlight>
<pre>
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# the line above to put the accentuated in the remarks
# la ligne ci dessus permet de mettre des accentué dans les remarques
# If this line is missing, an error will be returned
# si cette ligne est absente, une erreur sera renvoyée
# extract and use the coordinates of 3 objects selected
# extraire et utiliser les coordonnées de 3 points séléctionnés
import Part, FreeCAD, math, PartGui, FreeCADGui
import Part, FreeCAD, math, PartGui, FreeCADGui
from FreeCAD import Base, Console
from FreeCAD import Base, Console
sel = FreeCADGui.Selection.getSelection() # " sel " renferme les points sélectionnes
sel = FreeCADGui.Selection.getSelection() # " sel " contains the items selected
if len(sel)!=3 :
if len(sel)!=3 :
# If there are no 3 objects selected, an error is displayed in the report view
# s'il n'y a pas 3 objets sélectionnés, une erreur s'affiche dans la Vue rapport
# Le \r et \n en fin de ligne signifient Retour chariot et le Saut de ligne CR + LF.
# The \r and \n at the end of line mean return and the newline CR + LF.
Console.PrintError("Sélectionnez 3 points exactement\r\n")
Console.PrintError("Select 3 points exactly\r\n")
else :
else :
points=[]
points=[]
Line 362: Line 333:


for pt in points:
for pt in points:
# display of the coordinates in the report view
# affichage des coordonnées dans la Vue rapport
Console.PrintMessage(str(pt.x)+"\r\n")
Console.PrintMessage(str(pt.x)+"\r\n")
Console.PrintMessage(str(pt.y)+"\r\n")
Console.PrintMessage(str(pt.y)+"\r\n")
Line 368: Line 339:


Console.PrintMessage(str(pt[1]) + "\r\n")
Console.PrintMessage(str(pt[1]) + "\r\n")
</syntaxhighlight>
</pre>


===Lister les objets===
===List all objects===
<syntaxhighlight>
<pre>
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import FreeCAD,Draft
# Liste les objets
# List all objects of the document
App.ActiveDocument=App.getDocument("Unnamed")
doc = FreeCAD.ActiveDocument
doc = FreeCAD.ActiveDocument
print "Nom du document : ", doc.Name
objs = FreeCAD.ActiveDocument.Objects
objs = FreeCAD.ActiveDocument.Objects
#App.Console.PrintMessage(str(objs) + "\n")
#print objs
#print len(FreeCAD.ActiveDocument.Objects)
#App.Console.PrintMessage(str(len(FreeCAD.ActiveDocument.Objects)) + " Objects" + "\n")

for obj in objs:
for obj in objs:
name = obj.Name # liste le nom des objets
a = obj.Name # list the Name of the object (not modifiable)
print name # affiche le nom de l'objet
b = obj.Label # list the Label of the object (modifiable)
try:
#doc.removeObject("Ortho") # efface l'objet désigné
c = obj.LabelText # list the LabeText of the text (modifiable)
</pre>
App.Console.PrintMessage(str(a) +" "+ str(b) +" "+ str(c) + "\n") # Displays the Name the Label and the text
except:
App.Console.PrintMessage(str(a) +" "+ str(b) + "\n") # Displays the Name and the Label of the object


#doc.removeObject("Box") # Clears the designated object
===Fonction résidente avec action au clic de souris===
</syntaxhighlight>
<pre>

===Function resident with the mouse click action===
<syntaxhighlight>
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# provoque une action au clic de souris sur un objet
# causes an action to the mouse click on an object
# cette fonction reste résidente (en mémoire) grâce à "addObserver(s)"
# This function remains resident (in memory) with the function "addObserver(s)"
# "removeObserver(s) # désinstalle la fonction résidente
# "removeObserver(s) # Uninstalls the resident function
class SelObserver:
class SelObserver:
def addSelection(self,doc,obj,sub,pnt): # Sélection
def addSelection(self,doc,obj,sub,pnt): # Selection
print "addSelection"
App.Console.PrintMessage("addSelection"+ "\n")
print doc # Nom du document
App.Console.PrintMessage(str(doc)+ "\n") # Name of the document
print obj # Nom de l'objet
App.Console.PrintMessage(str(obj)+ "\n") # Name of the object
print sub # Nom de la partie de l'objet
App.Console.PrintMessage(str(sub)+ "\n") # The part of the object name
print pnt # Coordonnées de l'objet
App.Console.PrintMessage(str(pnt)+ "\n") # Coordinates of the object
App.Console.PrintMessage("______"+ "\n")


def removeSelection(self,doc,obj,sub): # Effacer l'objet sélectionné
def removeSelection(self,doc,obj,sub): # Delete the selected object
print "removeSelection"
App.Console.PrintMessage("removeSelection"+ "\n")
def setSelection(self,doc): # Sélection dans ComboView
def setSelection(self,doc): # Selection in ComboView
print "setSelection"
App.Console.PrintMessage("setSelection"+ "\n")
def clearSelection(self,doc): # Si clic sur l'écran, éffacer la sélection
def clearSelection(self,doc): # If click on the screen, clear the selection
print "clearSelection" # Si clic sur un autre objet, éfface le précédent
App.Console.PrintMessage("clearSelection"+ "\n") # If click on another object, clear the previous object
s =SelObserver()
FreeCADGui.Selection.addObserver(s) # install the function mode resident
#FreeCADGui.Selection.removeObserver(s) # Uninstall the resident function
</syntaxhighlight>


===List the components of an object===
s=SelObserver()
<syntaxhighlight>
FreeCADGui.Selection.addObserver(s) # installe la fonction en mode résident
#FreeCADGui.Selection.removeObserver(s) # désinstalle la fonction résidente
</pre>

===Lister les composantes d'un objet===
<pre>
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# This function list the components of an object
# This function list the components of an object
Line 509: Line 486:


detail()
detail()
</syntaxhighlight>
</pre>

===Lister les PropertiesList===


===List the PropertiesList===
<syntaxhighlight>
<syntaxhighlight>
o = App.ActiveDocument.ActiveObject
o = App.ActiveDocument.ActiveObject
Line 519: Line 495:
print "Property: ", p, " Value: ", o.getPropertyByName (p)
print "Property: ", p, " Value: ", o.getPropertyByName (p)
</syntaxhighlight>
</syntaxhighlight>
{{docnav|Embedding FreeCAD|Line drawing function}}


[[Category:Poweruser Documentation]]
[[Category:Python Code]]
[[Category:Tutorials]]


{{clear}}
{{docnav/fr|Embedding FreeCAD/fr|Line drawing function/fr}}
<languages/>

{{languages/fr | {{en|Code snippets}} {{es|Code snippets/es}} {{it|Code snippets/it}} {{se|Code snippets/se}} }}

[[Category:Poweruser Documentation/fr]]
[[Category:Python Code/fr]]
[[Category:Tutorials/fr]]

Revision as of 20:26, 15 May 2014

This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...


A typical InitGui.py file

Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.

 class ScriptWorkbench (Workbench): 
     MenuText = "Scripts"
     def Initialize(self):
         import Scripts # assuming Scripts.py is your module
         list = ["Script_Cmd"] # That list must contain command names, that can be defined in Scripts.py
         self.appendToolbar("My Scripts",list) 
         
 Gui.addWorkbench(ScriptWorkbench())

A typical module file

This is an example of a main module file, containing everything your module does. It is the Scripts.py file invoked by the previous example. You can have all your custom commands here.

 import FreeCAD, FreeCADGui 
 
 class ScriptCmd: 
    def Activated(self): 
        # Here your write what your ScriptCmd does...
        FreeCAD.Console.PrintMessage('Hello, World!')
    def GetResources(self): 
        return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'} 
       
 FreeCADGui.addCommand('Script_Cmd', ScriptCmd())

Import a new filetype

Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:

This line must be added to the InitGui.py file to add the new file extension to the list:

 # Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
 FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")

Then in the Import_Ext.py file:

 def open(filename): 
    doc=App.newDocument()
    # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
    doc.recompute()

To export your document to some new filetype works the same way, except that you use:

FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext") 

Adding a line

A line simply has 2 points.

 import Part,PartGui 
 doc=App.activeDocument() 
 # add a line element to the document and set its points 
 l=Part.Line()
 l.StartPoint=(0.0,0.0,0.0)
 l.EndPoint=(1.0,1.0,1.0)
 doc.addObject("Part::Feature","Line").Shape=l.toShape() 
 doc.recompute()

Adding a polygon

A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

 import Part,PartGui 
 doc=App.activeDocument()
 n=list() 
 # create a 3D vector, set its coordinates and add it to the list 
 v=App.Vector(0,0,0) 
 n.append(v) 
 v=App.Vector(10,0,0) 
 n.append(v) 
 #... repeat for all nodes 
 # Create a polygon object and set its nodes 
 p=doc.addObject("Part::Polygon","Polygon") 
 p.Nodes=n 
 doc.recompute()

Adding and removing an object to a group

 doc=App.activeDocument() 
 grp=doc.addObject("App::DocumentObjectGroup", "Group") 
 lin=doc.addObject("Part::Feature", "Line")
 grp.addObject(lin) # adds the lin object to the group grp
 grp.removeObject(lin) # removes the lin object from the group grp

Note: You can even add other groups to a group...

Adding a Mesh

 import Mesh
 doc=App.activeDocument()
 # create a new empty mesh
 m = Mesh.Mesh()
 # build up box out of 12 facets
 m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0)
 m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0)
 m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0)
 m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0)
 m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0)
 m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0)
 m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0)
 m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0)
 m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0)
 m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0)
 m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0)
 m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0)
 # scale to a edge langth of 100
 m.scale(100.0)
 # add the mesh to the active document
 me=doc.addObject("Mesh::Feature","Cube")
 me.Mesh=m

Adding an arc or a circle

 import Part
 doc = App.activeDocument()
 c = Part.Circle() 
 c.Radius=10.0  
 f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature 
 f.Shape = c.toShape() # Assign the circle shape to the shape property 
 doc.recompute()

Accessing and changing representation of an object

Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...

 gad=Gui.activeDocument()   # access the active document containing all 
                           # view representations of the features in the
                           # corresponding App document 
 
 v=gad.getObject("Cube")    # access the view representation to the Mesh feature 'Cube' 
 v.ShapeColor               # prints the color to the console 
 v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white

Observing mouse events in the 3D viewer via Python

The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.

 App.newDocument()
 v=Gui.activeDocument().activeView()
 
 #This class logs any mouse button events. As the registered callback function fires twice for 'down' and
 #'up' events we need a boolean flag to handle this.
 class ViewObserver:
    def logPosition(self, info):
        down = (info["State"] == "DOWN")
        pos = info["Position"]
        if (down):
            FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\n")
       
 o = ViewObserver()
 c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)

Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call

 v.removeEventCallback("SoMouseButtonEvent",c)

The following event types are supported

  • SoEvent -- all kind of events
  • SoButtonEvent -- all mouse button and key events
  • SoLocation2Event -- 2D movement events (normally mouse movements)
  • SoMotion3Event -- 3D movement events (normally spaceball)
  • SoKeyboardEvent -- key down and up events
  • SoMouseButtonEvent -- mouse button down and up events
  • SoSpaceballButtonEvent -- spaceball button down and up events

The Python function that can be registered with addEventCallback() expects a dictionary. Depending on the watched event the dictionary can contain different keys.

For all events it has the keys:

  • Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ...
  • Time -- the current time as string
  • Position -- a tuple of two integers, mouse position
  • ShiftDown -- a boolean, true if Shift was pressed otherwise false
  • CtrlDown -- a boolean, true if Ctrl was pressed otherwise false
  • AltDown -- a boolean, true if Alt was pressed otherwise false

For all button events, i.e. keyboard, mouse or spaceball events

  • State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases

For keyboard events:

  • Key -- a character of the pressed key

For mouse button event

  • Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY

For spaceball events:

  • Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY

And finally motion events:

  • Translation -- a tuple of three floats
  • Rotation -- a quaternion for the rotation, i.e. a tuple of four floats

Manipulate the scenegraph in Python

It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.

 from pivy.coin import *                # load the pivy module
 view = Gui.ActiveDocument.ActiveView   # get the active viewer
 root = view.getSceneGraph()            # the root is an SoSeparator node
 root.addChild(SoCube())
 view.fitAll()

The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python. However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with

 type = SoType.fromName("SoFCSelection")
 node = type.createInstance()

Adding and removing objects to/from the scenegraph

Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):

 from pivy import coin
 sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
 co = coin.SoCoordinate3()
 pts = [[0,0,0],[10,0,0]]
 co.point.setValues(0,len(pts),pts)
 ma = coin.SoBaseColor()
 ma.rgb = (1,0,0)
 li = coin.SoLineSet()
 li.numVertices.setValue(2)
 no = coin.SoSeparator()
 no.addChild(co)
 no.addChild(ma)
 no.addChild(li)
 sg.addChild(no)

To remove it, simply issue:

 sg.removeChild(no)

Adding custom widgets to the interface

You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PyQt4.

The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):

 class myWidget_Ui(object):
  def setupUi(self, myWidget):
    myWidget.setObjectName("my Nice New Widget")
    myWidget.resize(QtCore.QSize(QtCore.QRect(0,0,300,100).size()).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget
 
    self.label = QtGui.QLabel(myWidget) # creates a label
    self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
    self.label.setObjectName("label") # sets its name, so it can be found by name
 
  def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets
    myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
    self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))

Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:

  app = QtGui.qApp
  FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
  myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget
  myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script
  myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
  FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Adding a Tab to the Combo View

The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.

 from PyQt4 import QtGui,QtCore
 from PyQt4 import uic
 #from PySide import QtGui,QtCore
 
 def getMainWindow():
    "returns the main window"
    # using QtGui.qApp.activeWindow() isn't very reliable because if another
    # widget than the mainwindow is active (e.g. a dialog) the wrong widget is
    # returned
    toplevel = QtGui.qApp.topLevelWidgets()
    for i in toplevel:
        if i.metaObject().className() == "Gui::MainWindow":
            return i
    raise Exception("No main window found")
 
 def getComboView(mw):
    dw=mw.findChildren(QtGui.QDockWidget)
    for i in dw:
        if str(i.objectName()) == "Combo View":
            return i.findChild(QtGui.QTabWidget)
    raise Exception("No tab widget found")
 
 mw = getMainWindow()
 tab = getComboView(getMainWindow())
 tab2=QtGui.QDialog()
 tab.addTab(tab2,"A Special Tab")
 uic.loadUi("/myTaskPanelforTabs.ui",tab2)
 tab2.show()
 
 #tab.removeTab(2)

Opening a custom webpage

 import WebGui
 WebGui.openBrowser("http://www.example.com")

Getting the HTML contents of an opened webpage

 from PyQt4 import QtGui,QtWebKit
 a = QtGui.qApp
 mw = a.activeWindow()
 v = mw.findChild(QtWebKit.QWebFrame)
 html = unicode(v.toHtml())
 print html

Retrieve and use the coordinates of 3 selected points or objects

# -*- coding: utf-8 -*-
# the line above to put the accentuated in the remarks
# If this line is missing, an error will be returned
# extract and use the coordinates of 3 objects selected
import Part, FreeCAD, math, PartGui, FreeCADGui
from FreeCAD import Base, Console
sel = FreeCADGui.Selection.getSelection() # " sel " contains the items selected
if len(sel)!=3 :
  # If there are no 3 objects selected, an error is displayed in the report view
  # The \r and \n at the end of line mean return and the newline CR + LF.
  Console.PrintError("Select 3 points exactly\r\n")
else :
  points=[]
  for obj in sel:
    points.append(obj.Shape.BoundBox.Center)

  for pt in points:
    # display of the coordinates in the report view
    Console.PrintMessage(str(pt.x)+"\r\n")
    Console.PrintMessage(str(pt.y)+"\r\n")
    Console.PrintMessage(str(pt.z)+"\r\n")

  Console.PrintMessage(str(pt[1]) + "\r\n")

List all objects

# -*- coding: utf-8 -*-
import FreeCAD,Draft
# List all objects of the document
doc = FreeCAD.ActiveDocument
objs = FreeCAD.ActiveDocument.Objects
#App.Console.PrintMessage(str(objs) + "\n")
#App.Console.PrintMessage(str(len(FreeCAD.ActiveDocument.Objects)) + " Objects"  + "\n")

for obj in objs:
    a = obj.Name                                             # list the Name  of the object  (not modifiable)
    b = obj.Label                                            # list the Label of the object  (modifiable)
    try:
        c = obj.LabelText                                    # list the LabeText of the text (modifiable)
        App.Console.PrintMessage(str(a) +" "+ str(b) +" "+ str(c) + "\n") # Displays the Name the Label and the text
    except:
        App.Console.PrintMessage(str(a) +" "+ str(b) + "\n") # Displays the Name and the Label of the object

#doc.removeObject("Box") # Clears the designated object

Function resident with the mouse click action

# -*- coding: utf-8 -*-
# causes an action to the mouse click on an object
# This function remains resident (in memory) with the function "addObserver(s)"
# "removeObserver(s) # Uninstalls the resident function
class SelObserver:
    def addSelection(self,doc,obj,sub,pnt):               # Selection
        App.Console.PrintMessage("addSelection"+ "\n")
        App.Console.PrintMessage(str(doc)+ "\n")          # Name of the document
        App.Console.PrintMessage(str(obj)+ "\n")          # Name of the object
        App.Console.PrintMessage(str(sub)+ "\n")          # The part of the object name
        App.Console.PrintMessage(str(pnt)+ "\n")          # Coordinates of the object
        App.Console.PrintMessage("______"+ "\n")

    def removeSelection(self,doc,obj,sub):                # Delete the selected object
        App.Console.PrintMessage("removeSelection"+ "\n")
    def setSelection(self,doc):                           # Selection in ComboView
        App.Console.PrintMessage("setSelection"+ "\n")
    def clearSelection(self,doc):                         # If click on the screen, clear the selection
        App.Console.PrintMessage("clearSelection"+ "\n")  # If click on another object, clear the previous object
s =SelObserver()
FreeCADGui.Selection.addObserver(s)                       # install the function mode resident
#FreeCADGui.Selection.removeObserver(s)                   # Uninstall the resident function

List the components of an object

# -*- coding: utf-8 -*-
# This function list the components of an object
# and extract this object its XYZ coordinates,
# its edges and their lengths center of mass and coordinates
# its faces and their center of mass
# its faces and their surfaces and coordinates
# 8/05/2014

import Draft,Part
def detail():
    sel = FreeCADGui.Selection.getSelection()   # Select an object
    if len(sel) != 0:                           # If there is a selection then
        Vertx=[]
        Edges=[]
        Faces=[]
        compt_V=0
        compt_E=0
        compt_F=0
        pas    =0
        perimetre = 0.0   
        EdgesLong = []

        # Displays the "Name" and the "Label" of the selection
        App.Console.PrintMessage("Selection > " + str(sel[0].Name) + "  " + str(sel[0].Label) +"\n"+"\n")

        for j in enumerate(sel[0].Shape.Edges):                                     # Search the "Edges" and their lengths
            compt_E+=1
            Edges.append("Edge%d" % (j[0]+1))
            EdgesLong.append(str(sel[0].Shape.Edges[compt_E-1].Length))
            perimetre += (sel[0].Shape.Edges[compt_E-1].Length)                     # calculates the perimeter

            # Displays the "Edge" and its length
            App.Console.PrintMessage("Edge"+str(compt_E)+" Length > "+str(sel[0].Shape.Edges[compt_E-1].Length)+"\n")

            # Displays the "Edge" and its center mass
            App.Console.PrintMessage("Edge"+str(compt_E)+" Center > "+str(sel[0].Shape.Edges[compt_E-1].CenterOfMass)+"\n")

            num = sel[0].Shape.Edges[compt_E-1].Vertexes[0]
            Vertx.append("X1: "+str(num.Point.x))
            Vertx.append("Y1: "+str(num.Point.y))
            Vertx.append("Z1: "+str(num.Point.z))
            # Displays the coordinates 1
            App.Console.PrintMessage("X1: "+str(num.Point[0])+" Y1: "+str(num.Point[1])+" Z1: "+str(num.Point[2])+"\n")

            try:
                num = sel[0].Shape.Edges[compt_E-1].Vertexes[1]
                Vertx.append("X2: "+str(num.Point.x))
                Vertx.append("Y2: "+str(num.Point.y))
                Vertx.append("Z2: "+str(num.Point.z))
            except:
                Vertx.append("-")
                Vertx.append("-")
                Vertx.append("-")
            # Displays the coordinates 2
            App.Console.PrintMessage("X2: "+str(num.Point[0])+" Y2: "+str(num.Point[1])+" Z2: "+str(num.Point[2])+"\n")

            App.Console.PrintMessage("\n")
        App.Console.PrintMessage("Perimeter of the form  : "+str(perimetre)+"\n") 

        App.Console.PrintMessage("\n")
        FacesSurf = []
        for j in enumerate(sel[0].Shape.Faces):                                      # Search the "Faces" and their surface
            compt_F+=1
            Faces.append("Face%d" % (j[0]+1))
            FacesSurf.append(str(sel[0].Shape.Faces[compt_F-1].Area))

            # Displays 'Face' and its surface
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Surface "+str(sel[0].Shape.Faces[compt_F-1].Area)+"\n")

            # Displays 'Face' and its CenterOfMass
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Center  "+str(sel[0].Shape.Faces[compt_F-1].CenterOfMass)+"\n")

            # Displays 'Face' and its Coordinates
            FacesCoor = []
            fco = 0
            for f0 in sel[0].Shape.Faces[compt_F-1].Vertexes:                        # Search the Vertexes of the face
                fco += 1
                FacesCoor.append("X"+str(fco)+": "+str(f0.Point.x))
                FacesCoor.append("Y"+str(fco)+": "+str(f0.Point.y))
                FacesCoor.append("Z"+str(fco)+": "+str(f0.Point.z))

            # Displays 'Face' and its Coordinates
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Coordinate"+str(FacesCoor)+"\n")

            # Displays 'Face' and its Volume
            App.Console.PrintMessage("Face"+str(compt_F)+" >  Volume  "+str(sel[0].Shape.Faces[compt_F-1].Volume)+"\n")
            App.Console.PrintMessage("\n")

        # Displays the total surface of the form
        App.Console.PrintMessage("Surface of the form    : "+str(sel[0].Shape.Area)+"\n")

        # Displays the total Volume of the form
        App.Console.PrintMessage("Volume  of the form    : "+str(sel[0].Shape.Volume)+"\n")

detail()

List the PropertiesList

o = App.ActiveDocument.ActiveObject
op = o.PropertiesList
for p in op:
    print "Property: ", p, " Value: ", o.getPropertyByName (p)
Embedding FreeCAD
Line drawing function