Python Development Environment/fr

Un environnement de développement simplifié pour Python au sein de FreeCAD
Python est un environnement de programmation qui a été intégré au système FreeCAD. En utilisant Python, de nombreuses opérations offertes par FreeCAD sont disponibles pour être programmer. Les programmes Python dans FreeCAD sont généralement développés pour être exécutés soit sur la console Python, soit par le biais de fonction Macro de FreeCAD (voir Comment installer des macros).

Il existe de nombreux outils disponibles pour le développement de programmes en Python. Les facteurs qui compliquent le développement de Python pour une utilisation avec FreeCAD sont de deux ordres : premièrement, les outils n'ont aucun support pour les nombreuses structures de données et les points d'accès de FreeCAD ; deuxièmement, ils ne fonctionnent pas "dans FreeCAD". Cela signifie que vous pouvez les utiliser pour développer du code en dehors de FreeCAD et ne pas être en mesure de tester dans l'environnement cible, ou vous pouvez développer Python dans l'environnement cible (c'est-à-dire l'environnement FreeCAD) mais ne pas avoir de support des outils de développement. Aucune de ces solutions n'est acceptable.

Contexte
Le développement de logiciels modernes au niveau commercial se fait généralement à l'aide d'un ensemble d'outils génériquement appelés 'IDE' pour Environnement de développement. En général, ces outils comprennent les éléments suivants 3 :


 * éditeur du code source
 * outils d'automatisation du build
 * débogueur

qui sont standard tandis que les suivantes sont présentes dans certains IDE mais pas dans d'autres :


 * complétion de code intelligente
 * compilateur, interpréteur ou les deux intégrés
 * système de contrôle de version
 * construction d'une interface utilisateur graphique (GUI)
 * navigateur de classes
 * navigateur d'objets
 * diagramme de hiérarchie des classes

Un résumé du statut de ces outils dans FreeCAD est ('N/D' signifiant 'Non disponible') :

De nombreux outils existent pour supporter la fonction ci-dessus pour la programmation Python mais malheureusement ils ne s'intègrent pas à l'environnement de développement FreeCAD.

Une liste d'IDE pour Python se trouve à l'adresse Integrated Development Environments for Python.

Éditeurs
Il y a un éditeur pour Python qui fait partie de FreeCAD, il est lancé en cliquant sur le bouton Editer de Macro->Macros.... Si vous souhaitez utiliser un éditeur tiers qui tire parti de votre plate-forme, il existe plusieurs éditeurs Python disponibles, pour de nombreuses plates-formes et avec différents niveaux de fonctionnalité. Un avantage de l'utilisation d'un éditeur externe est que la zone d'affichage de FreeCAD peut être utilisée pour la sortie (à la fois graphique et textuelle vers la console) alors que le code source est affiché dans une autre application. Une liste d'éditeurs Python pour diverses plateformes est disponible à l'adresse Python Editors.

Remarque : Pour Macintosh, l'éditeur de texte TextWrangler fonctionne bien. Il possède une mise en évidence du code et d'excellentes facilités de recherche. Il existe des options pour exécuter des travaux en Python, mais bien sûr, elles ne fonctionnent pas avec l'environnement FreeCAD.

Répertoires du code source macro
Il y a deux répertoires utilisés par FreeCAD, par défaut c'est le même répertoire mais ils sont pointés par différents points d'appel dans FreeCAD :
 * FreeCAD.ConfigGet("UserAppData")
 * FreeCAD.ParamGet('User parameter:BaseApp/Preferences/Macro').GetString('MacroPath')

Le premier, "UserAppData", pointe vers un répertoire où peuvent être stockés des éléments tels que des fichiers de configuration ou d'autres fichiers destinés à l'utilisateur mais que celui-ci ne doit pas modifier.

Le second "MacroPath" pointe vers un répertoire où sont stockés les fichiers Python qui sont des fichiers macro pour FreeCAD. Pour marquer un fichier Python comme un fichier macro pour FreeCAD, l'extension du fichier est modifiée de ".py" à ".FCMacro".

Par défaut, ces deux répertoires sont au même endroit, mais ce n'est pas nécessaire. Il peut être pratique de modifier l'emplacement des fichiers de macro (*.FCMacro) à un autre endroit.

Editing files located in the "MacroPath" is straight forward, the text editor will accommodate this. For ease of use of FreeCAD Macro files, it is advisable to keep all the macro files in the directory pointed to by "MacroPath".

To alter the "MacroPath" directory, use Tools->Edit Parameters and then select Preferences/Macro/MacroPath where the text may be double-clicked and edited. Alternatively "MacroPath" can be altered by the code:

Debugger
Debuggers typically provide two main features (amongst others):
 * breakpoints in the source code
 * variable inspection

Breakpoints are 'traps' that are placed in the code, if the execution path through the code encounters one of these breakpoints, then execution is halted or suspended. Note that execution is not stopped as when a program is stopped all memory resident information such as variables is lost. While the program is suspended the contents of variables can be inspected and sometimes altered (which depends on the ability of the debugger). Generally the source code can not be changed although some environments do support this. When ready, the execution of the source code can be resumed. Numerous breakpoints can be placed in the code and numerous suspensions through the breakpoints may occur. The purpose of the debugger is to make sure that the execution with the breakpoints and suspensions is functionally identical to execution without breakpoints.

Variable Inspections are available during the suspension of execution caused by a breakpoint. Generally the contents of variables can be viewed, many debuggers also support the editing of the contents before execution resumes.

Although a fully functioned debugger is planned for FreeCAD it is not available as of yet. This section will detail some work-arounds for the interim until the debugger is released.

Breakpoints
Implementing breakpoints involves a supervisory level of code which administers the execution of the code under development. Such a level of code for Python development within FreeCAD is not presently available. As a weak substitute, the following code is an option. Instead of suspending the execution the code will halt execution completely by dividing a number by zero. This really is a very weak option compared to a proper debugger breakpoint, also this option is only of use when used alongside the routine shown in the next section 'Variable Inspection'.

Breakpoint Code

Console Traceback

When a program fails during execution, Python generates what is known as a traceback which lists the order of program execution (i.e. which program called which program in which order).

For the code sample

we get the following traceback:

Reading the traceback we can determine that:
 * a message of 'Breakpoint: amalgamation routine' was sent by the breakpoint which has the string 'amalgamation routine'
 * the execution error occurred at line 28 of module 'myNewMacro'
 * routine 'myNewMacro' was called from line 40 in the module 'testStub'

Assuming the string passed to the breakpoint call is meaningful then the location of the breakpoint can easily be determined. Note that is a complex system the traceback may have tens or even hundreds of entries in it.

To become productive with these breakpoints, continue on to the next section.

Variable Inspection
The second main feature of a debugger is to examine and possibly alter the contents of variables. Once again, until the FreeCAD debugger for Python is ready we have to depend on work-arounds.

A feature of the FreeCAD system is the provision of global variables. These variables that are created by the Python code and exist in FreeCAD's memory until the user Quits from FreeCAD. The form of these variables is:

The statement creates a Python variable in the FreeCAD memory which is fully accessible to Python code, in fact it behaves identically to a normal Python variable. Yet after the Python code finishes running, no matter if it is running as a macro or through the console, there will be a variable 'FreeCAD.myVariable' remaining in memory with the value of 123. Entering:

will produce the contents of the variable on the console. This value will remain in FreeCAD until either it is changed or the user Quits from FreeCAD. This means the value is present and available for a subsequent Python program to read from. At any time it can be checked from the console by typing it's name. So a program called 'Program A':

can run and load values into the global variable. Later a second program called 'Program B' can run and retrieve the value:

Presumably 'Program B' then goes on to make calculations involving the values left in FreeCAD.myVariable. At any time the user can type on the console to inspect the variable contents:

An important fact to be aware of with FreeCAD global variables is that they exist in memory and are lost when the program is Quit from. They are not saved with documents but only exist in memory.

Usage
This brings us to a point where we can put the two steps together and use them to trace down errors in code. This is a bit cumbersome to use but is only the option until the FreeCAD debugger is ready.

It's probably easiest to present through an example, say the following program is being debugged:

Execution of the program on the console yields:

which is not what we expected! Assuming we are unable to see the errors we can use our unsophisticated breakpoint and variable examiner as follows. We can insert a line to copy the value of the variable we are wondering about to a global variable, then we can place a breakpoint to halt execution there:

Now when we run the program we get:

Probably things don't look so good, but what we can now do is inspect the value of the Python variable 'temporaryVariable1' as we assigned it's value to the global variable 'FreeCAD.saveMyVariable':

Remembering that the variable 'FreeCAD.saveMyVariable' holds the value of the Python variable 'temporaryVariable1' we can now determine the error in the value and start tracing back to determine where the error came from. When we are looking at 'FreeCAD.saveMyVariable' it is important to realise that the variable 'temporaryVariable1' is no longer available - it has been garbage collected away by the Python system.

Once the error has been located in the statement

and corrected to:

Then we can run the program again, and get the value of '11' which is still not right. We can make more assignments to FreeCAD global variables, have multiple breakpoints (although the first one encountered will stop execution)

We now have two breakpoints (although one is commented out) and two FreeCAD global variables in use. There is no practical limit to the global variables available from FreeCAD so there is no need to economise unnecessarily. We can now produce the following on the console:

Some points about the use of the FreeCAD global variables:
 * Python treats these variables identically to any other Python variable
 * these variables may hold any Python data type - anything a regular Python variable would hold
 * these variables may be used to 'bring out' the contents of a Python variable so we can see them
 * also these variables may be used to 'supply' values to a Python variable by setting their value from the console prior to running a routine, or setting it in a previous Python program
 * these variables may be used to pass data between two programs that run at different points in time
 * (to repeat) these variables are only for the duration of the FreeCAD session, once the user Quits from FreeCAD then the variables are lost

Variable Watcher
There is a utility Global Variable Watcher to help monitor the global variables of FreeCAD. It can display the contents of a global variable either on request or on a timed basis.

Name Space Clash
One thing to be aware of is as there is no management of global variable names by FreeCAD so there is the possibility of changing a variable from the system or another piece of code. Consequently it is a good idea to prefix your variables with something unique such as the routine name. For example to use a variablefrom a routine called 'alpha1' the global name could be 'FreeCAD.alpha1MyVariable'.

Coding Framework
When developing small pieces of Python code in FreeCAD it may be sufficient to use the Python console. However as the number of lines of code grows it makes more sense to store them in a file. Python can be in any file ending with the extension ".py", however FreeCAD also provides a mechanism called Macro for storing such programs and interacting with them (e.g. editing, running). Python in regular '.py' files may only run from the Python console while python in macro file '.FCMacro' can be run from the FreeCAD interface for executing macros. One downside with the FreeCAD menu interface is it is menu based with a control window and potentially causes some clutter on the on-screen GUI.

An easier approach is to take the Python code and instead of starting it from the FreeCAD Macro menu, start it from a toolbar. A Python routine linked to a button on a toolbar may be executed by one click. Also as the toolbars are floating windows they do not clutter the on-screen display. In fact if the FreeCAD window is less then the physical size of the screen the toolbar may be left to float outside of the FreeCAD window. This is beneficial when screen snapshots are required of the FreeCAD display. Also the toolbar can be much smaller than the macro control window displayed by the Macro menu of FreeCAD.

Connecting a macro to a button on a toolbar is covered in How to Install Macros and How to Customise a Toolbar. It can take a number of minutes to connect a macro to button on toolbar, select an icon etc. This is not always required as sometimes you simply want to quickly flesh out a piece of code which will then be integrated in some other code. For this situation a Test Stub can be beneficial. There is no real definition for what a test stub would entail, it really depends on the person and the application area. An example is shown below:

This test stub also serves as a template for code with locations defined for the different aspects of a large Python program. When executed the test stub program simply generates a message showing it's name and finishes. In using a test stub, any main line code written is placed at the very end of the file with code for class definition, functions etc. placed in the previous sections. The template can easily be altered to match the situation. Obviously for a program of 5 lines there is no need for such an amount of documentation.

By keeping a button permanently on a toolbar and linking that button to the test sub, there is always an area to write code and execute it immediately. The execution will be independent of the Python console. Also the execution can be independent of the screen GUI. Output from the program under development will appear as it should on the screen without any other artifacts from the programming environment. The Python console can be hidden to increase display area or used for any other purpose if needed. When execution is handled by the button on the toolbar the console is not required.

When the code is finished then is can simply be copied/pasted over to another file and the text stub left empty until the next time it is needed.

Multiple pieces of code can be developed using the same test stub with some extra code for providing multiple buttons which is located at PySide Beginner Examples - More Than 2 Buttons.

More PySide Support

For more support using the PySide GUI there is the page PySide

More Python Programming Support

For more assistance with Python coding, there is a macro written to aid in developing Python code, is it located at Python Assistant Window

Putting It All Together
Screen management can be a challenge when developing code that has complex and detailed graphical output like FreeCAD does. The following system works well:
 * FreeCAD for console, report, GUI display
 * toolbar to invoke code being developed
 * external editor to modify code
 * PAW (Python Assistant Window) to aid Python code generation

Screen Management

With the test stub operated from a toolbar, and an external editor used, the window layout on the screen will be something like:



"tree" in the diagram refers to the Combi or Tree browsers, the Python console and Report view are combined into the lower window and selectable by buttons. By selective use of the tools the development stream can be optimised, the above is only one idea. Tailoring is done on a personal basis.

Miscellaneous Links
Some other links about IDEs for Python which might be of interest are:
 * Comparison of Python IDEs for Development
 * Choosing the Best Python IDE
 * Your Development Environment
 * PyCharm Community Edition IDE