Introduction à Python

From FreeCAD Documentation
Revision as of 05:21, 10 September 2017 by Pascal (talk | contribs)

Ceci est un petit tutoriel créé pour ceux qui veulent débuter en programmation Python, qui est un langage de programmation open-source et multiplate-forme. Python a de nombreuses fonctionnalités qui le différencie des autre langages de programmation, et est facilement accessible à celui qui veut se lancer dans la programmation.

  • Il a été conçu spécialement pour être facile à lire par les êtres humains, il est ainsi facile à apprendre et à comprendre
  • Il est interprété. C'est-à-dire que contrairement aux langages compilés comme le C, votre programme n'a pas besoin d'être compilé pour être exécuté. Le code que vous écrivez peut être directement exécuté, une ligne après l'autre si vous le souhaitez. Cela permet de l'apprendre et de trouver les erreurs dans votre code facilement, parce que vous avancez lentement, une étape après l'autre.
  • Il peut être intégré dans d'autres programmes comme langage de script. FreeCAD possède un interpréteur Python intégré, vous pouvez ainsi y écrire du code Python. Cela permet de manipuler des éléments de FreeCAD, par exemple de créer des objets géométriques. Il s'agit d'une fonction extrêmement puissante, parce qu'au lieu de se contenter de cliquer sur un bouton appelé "Créer une sphère", qu'un programmeur aurait placé là pour vous, vous avez la possibilité de créer simplement vos propres outils pour générer exactement les objets géométriques que vous souhaitez.
  • Il est extensible; vous pouvez simplement installer de nouveaux modules Python et étendre ses fonctionnalités. Par exemple, il existe un module qui permet à Python de lire et d'écrire des images jpg, de communiquer avec twitter, de planifier des tâches exécutées pour votre système d'exploitation, etc...

Nous vous encourageons vivement à entrer les extraits de code ci-dessous dans un interpréteur Python. Pour beaucoup de nos exemples, le point important est la ligne après l'exécution du code, le résultat. Et maintenant au travail ! Soyez conscient que ce qui suit est une introduction simplifiée, et en aucun cas un tutoriel complet. Mais nous espérons qu'après cette lecture vous aurez acquis les bases nécessaires pour connaître et exploiter plus profondément les mécanismes de FreeCad.

L’interpréteur

Habituellement, lors de l'écriture d'un programme informatique, il suffit d'ouvrir votre environnement de programmation préféré qui, est dans la plupart des cas, un éditeur de texte avec plusieurs outils autour de lui, écrire votre programme, puis le compiler et l'exécuter. Lorsque vous avez fait des erreurs pendant l'écriture, votre programme ne fonctionnera pas! et vous obtiendrez un message d'erreur vous indiquant ce qu'il s'est passé. Ensuite, vous revenez à votre éditeur de texte, corrigez les erreurs, exécutez à nouveau, et ainsi de suite jusqu'à ce que votre programme fonctionne parfaitement.

En Python, tout ce processus, peut être exécuté de manière transparente dans l'interpréteur Python. L’interpréteur Python est une fenêtre avec une invite de commande, vous pouvez simplement y taper votre code Python. Si vous installez Python sur votre ordinateur (téléchargez le depuis le site web Python si vous êtes sous Windows ou Mac, installez le à partir des gestionnaire de paquets, si vous êtes sous GNU / Linux), vous aurez l'interpréteur Python dans votre menu de démarrage. Mais FreeCAD dispose également d'un interpréteur Python intégré, vous n'êtes donc pas obligé de l'installer, cet interpréteur est visible dans la fenêtre inférieure (Si vous ne voyez pas cette fenêtre, cliquez sur Affichage->Vues->Console Python). Tous ces exemples ont été relu à partir de l'interpréteur disponible dans FreeCad.

(SI vous ne l'avez pas, cliquez sur le menu Affichage --> Panneaux --> Console Python).

L’interpréteur affiche la version de Python installée, puis le symbole >>>, qui est l'invite de commande pour entrer votre code Python. L'écriture du code dans l'interpréteur est très simple: une ligne, est une instruction. Lorsque vous appuyez sur ENTREE, votre ligne de code est exécuté (après avoir été instantanément compilé et cela de manière transparente pour vous).

Par exemple, écrivez ce code:

print "hello"

Ici print est une commande spéciale de Python qui signifie: affiche ce que je te demande. Lorsque vous pressez ENTREE, l'opération s’exécute et le message hello s'affiche à l'écran. Si vous effectuez une erreur, par exemple, écrivez:

print hello

Python vous dira qu'il ne sait pas ce qu'est hello. Les caractères " (guillemets) spécifient que le contenu est une chaîne de caractères qui doit être affichée. Sans les " (guillemets), la commande d'affichage de hello n'est pas reconnue comme du texte, mais comme un mot-réservé spécial de Python. L'important est, que vous obtenez immédiatement une notification d'erreur. En appuyant sur la flèche Haut (ou, dans l'interpréteur FreeCAD, CTRL + flèche Haut), vous pouvez revenir à la dernière commande que vous avez écrite et la corriger.

L'interpréteur Python dispose également d'un système d'aide intégré. Essayez :

help

ou, par exemple, imaginons que nous n'avons pas compris ce qui n'allait pas avec notre commande d'affichage "help" ci-dessus, nous allons demander des informations spécifiques sur la commande "print". Tapez :

help("print")

Nous voilà devant une longue description sur la commande "print".

Maintenant que nous dominons totalement notre interpréteur, et nous pouvons commencer à travailler sérieusement.

Les Variables

Bien sûr, vous vous dites que l'affichage de hello n'est pas très intéressant. Il peut y avoir alors des choses plus intéressantes comme par exemple, l'affichage de choses que vous ne savez pas, et laisser Python trouver ces choses pour vous. C'est là que le concept de "variable" entre en jeu. Une variable est tout simplement une valeur que vous stockez en mémoire avec un nom identificateur. Par exemple, tapez ceci:

a = "hello"
print a

Je suppose que vous avez compris ce qui s'est passé ? Nous avons «sauvé» en mémoire la chaîne "hello" dans la variable qui porte le nom de a. Maintenant, a n'est plus un nom inconnu ! Nous pouvons maintenant l'utiliser n'importe où, comme par exemple dans la commande d'affichage à l'écran print. Nous pouvons dans Python utiliser n'importe quel nom que nous voulons, tout en respectant de simples règles, par exemple, ne pas utiliser d'espaces ou de signes de ponctuation. Par exemple, nous pouvons écrire:

hello = "my own version of hello"
print hello

Avez vous compris ? Maintenant hello n'est plus un mot inconnu. Que faire alors si, par inattention ou par méprise nous choisissons un nom qui existe dans Python? Admettons que nous voulons stocker notre chaîne sous le nom de "print":

print = "hello"

Python se rend compte immédiatement de l'erreur et vous signale qu'il est impossible de donner ce nom à votre variable. Il y a quelques restrictions dans Python, les mots "réservés" ne peuvent pas être modifiés! Mais, nos propres variables peuvent être modifiées à tout moment, c'est exactement pour cela qu'elles sont appelées variables, le contenu de la variable peut varier. Par exemple:

myVariable = "hello"
print myVariable
myVariable = "good bye"
print myVariable

Nous venons de changer la valeur de myVariable. Nous pouvons également copier des variables:

var1 = "hello"
var2 = var1
print var2

Notez qu'il est judicieux de donner des noms descriptifs à vos variables, lorsque vous écrivez un long programme, vous ne saurez plus à quoi sert votre variable "a". Mais, si vous la nommez, par exemple MonMessageDeBienvenue, vous vous souviendrez facilement a quoi vous l'aviez destinée quand vous la verrez.

Plus de renseignements sur les variables Python

La casse est très importante. Par exemple maVariable n'est pas identique à mavariable, la différence se situe dans la lettre majuscule/minuscule "v". Si vous saisissiez "print mavariable", vous aurez en retour une erreur de type : NameError: name is not defined.

Les Nombres

Vous savez qu'un programme informatique est utilisé pour traiter toutes sortes de données, non seulement du texte mais aussi et surtout des nombres. Une des choses les plus importantes dans Python, est que Python doit savoir quel type de données seront traitées. Nous avons vu dans notre exemple d'affichage "bonjour" que la commande d'affichage print a reconnu «bonjour» comme une chaîne. C'est grâce au " " " (guillemets), que la commande d'affichage print sait qu'il va traiter une chaîne de caractères alphabétiques (du texte).

Le type de donnée contenu dans une variable peut être connu à n'importe quel moment grâce à la commande spéciale de Python type():

myVar = "hello"
type(myVar)

Dans cet exemple, il s'affiche dans la console Python Template:SytemOutput' dans le langage informatique on dit qu'il est de type "string" (chaîne de caractères alphabétiques). Il y a d'autres types de données, par exemple: les nombres entier (integer) , les nombres à virgule flottante (float) . . .:

firstNumber = 10
secondNumber = 20
print firstNumber + secondNumber
type(firstNumber)

C'est déjà plus intéressant, n'est-ce pas? Maintenant nous avons une puissante calculatrice! Voyons maintenant comment elle fonctionne. Python sait que 10 et 20 sont des nombres entiers. Donc, ils sont stockés en mémoire sous forme "int" (integer), et Python peut travailler avec eux comme il peut le faire avec des nombres entiers. Regardez les résultats de ce code:

firstNumber = "10"
secondNumber = "20"
print firstNumber + secondNumber

See? We forced Python to consider that our two variables are not numbers but mere pieces of text. Python can add two pieces of text together, but it won't try to find out any sum. But we were talking about integer numbers. There are also float numbers. The difference is that integer numbers don't have decimal part, while float numbers can have a decimal part:

var1 = 13
var2 = 15.65
print "var1 is of type ", type(var1)
print "var2 is of type ", type(var2)

Les types entier et à virgule flottante, Int et Float peuvent être mélangés sans problème:

total = var1 + var2
print total
print type(total)

Of course the total has decimals, right? Then Python automatically decided that the result is a float. In several cases such as this one, Python automatically decides what type to use. In other cases it doesn't. For example:

varA = "hello 123"
varB = 456
print varA + varB

This will give us an error, varA is a string and varB is an int, and Python doesn't know what to do. However, we can force Python to convert between types:

varA = "hello"
varB = 123
print varA + str(varB)

Maintenant, l'opération fonctionne, pourquoi ! Vous avez noté, que nous avons converti varB en "string" au moment de l'affichage avec la commande str(), mais nous n'avons pas modifié le type de varB qui reste un int. Si nous voulons convertir varB de façon permanente en une chaîne de caractères pour les besoins futur du programme, nous aurons besoin de faire:

varB = str(varB)

Nous pouvons également utiliser les commandes int() et float() pour convertir une chaîne de caractères str en un int ou float Pour la conversion, il faut faire:

varA = "123"
print int(varA)
print float(varA)

Note au sujet des commandes Python

You must have noticed that in this section we used the print command in several ways. We printed variables, sums, several things separated by commas, and even the result of other Python command such as type(). Maybe you also saw that doing those two commands,

type(varA)
print type(varA)

have exactly the same result. That is because we are in the interpreter, and everything is automatically printed. When we write more complex programs that run outside the interpreter, they won't print automatically, so we'll need to use the print command. From now on, let's stop using it here, it'll go faster. So we can simply write:

myVar = "hello friends"
myVar

You must have seen that most of the Python commands (or keywords) type(), int(), str(), etc. have parenthesis to limit the command contents. The only exception is the print command, which in fact is not really an exception, as it also works normally: print("hello"). However, since it is used often, the Python designers allowed a simpler version.

Les Listes (Tableaux)

Another interesting data type is a list. A list is simply a collection of other data. The same way that we define a text string by using " ", we define a list by using [ ]:

myList = [1,2,3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

You see that it can contain any type of data. Lists are very useful because you can group variables together. You can then do all kinds of things within that group, for example counting them:

len(myOtherList)

ou récupérer un objet de cette liste:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

You see that while the len() command returns the total number of items in a list, their "position" in the list begins with 0. The first item in a list is always at position 0, so in our myOtherList, "Bob" will be at position 2. We can do much more with lists, you can read here, such as sorting contents, removing or adding elements.

A funny and interesting thing: a text string is very similar to a list of characters! Try doing this:

myvar = "hello"
len(myvar)
myvar[2]

Usually, what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Outside strings, ints, floats and lists, there are more built-in data types, such as dictionaries, or you can even create your own data types with classes.

L'Indentation

Une manière pratique et élégante d'afficher chaque élément de la liste, est de naviguer à l’intérieur de cette liste.
Entrez ce code dans la console:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
   print dalton + " Dalton"

We iterated (programming jargon) through our list with the "for ... in ..." command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that a colon (:) ended line has happened and more is coming.

How will Python know how many of the next lines will be to be executed inside the for...in operation? For that, Python uses indentation. That is, your next lines won't begin immediately. You will begin them with a blank space, or several blank spaces, or a tab, or several tabs. Other programming languages use other methods, like putting everything inside parenthesis, etc. As long as you write your next lines with the same indentation, they will be considered part of the for-in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you finished, just write another line without indentation, or simply press Enter to come back from the for-in block

Indentation is cool because it aids in program readability. If you use large indentations (for example use tabs instead of spaces because it's larger), when you write a big program you'll have a clear view of what is executed inside what. We'll see that commands other than for-in, can have indented blocks of code too.

For-in commands can be used for many things that must be done more than once. It can, for example, be combined with the range() command:

serie = range(1,11)
total = 0
print "sum"
for number in serie:
   print number
   total = total + number
print "----"
print total

(If you have been running the code examples in an interpreter by Copying and Pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste to the interpreter. In the interpreter issue an <enter> until the three dot prompt disappears and the code runs. Then copy the final two lines into the interpreter followed by one or more <enter> The final answer should appear.)

If you would type into the interpreter help(range) you would see:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the range parameters to be an integer using int()

decimales = 1000                     # for 3 decimales 
#decimales = 10000                   # for 4 decimales ...
for i in range(int(0 * decimales),int(180 * decimales),int(0.5 * decimales)):
    print float(i) / decimales

Ou des choses plus complexes comme ceci:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
   print alldaltons[n], " is Dalton number ", n

Vous voyez que la commande range() a également la particularité de commencer à 0 (si vous ne spécifiez pas un nombre de départ) et que son dernier nombre sera le nombre que vous aurez spécifié moins un . Bien sûr, cette commande fonctionne parfaitement avec les autres commandes Python.

Par exemple:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
   print alldaltons[n]

Une autre fonction intéressante utilisée dans un bloc indenté est la commande de condition if (si). Avec " if " la suite de la procédure sera exécutée uniquement si la condition est remplie.

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
   print "We found that Dalton!!!"

C'est bien, ce code affiche "OK il c'est bien un Dalton !!!" car la condition est exacte. Mais maintenant essayons cette ligne:

if "Lucky" in alldaltons:

Il ne c'est rien affiché car la condition n'était pas remplie. Nous pouvons alors lui demander else (si la condition n'est pas remplie alors):

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
   print "We found that Dalton!!!"
else:
   print "Such Dalton doesn't exist!"

Les Fonctions

There are few standard Python commands. In the current version of Python, there are about 30, and we already know several of them. But imagine if we could invent our own commands? Well, we can, and it's extremely easy. In fact, most the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

def printsqm(myValue):
   print str(myValue)+" square meters"
 
printsqm(45)

(Another copy and paste error, only copy through the end of the indented section i.e. " square meters" Paste to the interpreter, and issue <enter> until the three dot prompt goes a way, then copy and paste the final line.)

Extremely simple: the def() command defines a new function. You give it a name, and inside the parenthesis you define arguments that we'll use in our function. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len() alone, Python will tell you it needs an argument. That is, you want len() of something, right? Then, for example, you'll write len(myList) and you'll get the length of myList. Well, myList is an argument that you pass to the len() function. The len() function is defined in such a way that it knows what to do with what is passed to it. Same as we did here.

The "myValue" name can be anything, and it will be used only inside the function. It is just a name you give to the argument so you can do something with it, but it also serves to tell the function how many arguments to expect. For example, if you do this:

printsqm(45,34)

Cette commande affichera l'erreur "TypeError: printsqm() takes exactly 1 argument (2 given)" car la fonction "def printsqm(myValue):" ne demande qu'un seul argument, "myValue" et, nous lui en avons donné deux, 45 et 34.

Maintenant, écrivez cette fonction:

def sum(val1,val2):
   total = val1 + val2
   return total

sum(45,34)
myTotal = sum(45,34)

Nous avons créé une fonction qui demande deux arguments, les exécutes , et nous renvoie le résultat. Le retour du résultat est très utile car nous pouvons l'utiliser pour l'afficher ou le stocker dans une variable myTotal (pour notre exemple mais n'importe quel nom conviendra) ou les deux. Comme nous sommes dans l'interpréteur de Python, le résultat s'affiche en faisant:

sum(45,34)

will print the result on the screen, but outside the interpreter, since there is no print command inside the function, nothing would appear on the screen. You would need to:

print sum(45,34)

Voilà c'est affiché.

Pour plus de renseignements sur les autres possibilités des fonctions.

Les Modules

Maintenant, vous avez une idée du fonctionnement de Python: mais comment faire pour travailler avec les fichiers et les modules.

Until now, we wrote Python instructions line by line in the interpreter, right? What if we could write several lines together, and have them executed all at once? It would certainly be handier for doing more complex things. And we could save our work too. Well, that too, is extremely easy. Simply open a text editor (such as the windows notepad, Linux gedit, emacs, or vi), and write all your Python lines, the same way as you write them in the interpreter, with indentations, etc. Then, save that file somewhere, preferably with a .py extension. That's it, you have a complete Python program. Of course, there are much better editors than notepad, but it is just to show you that a Python program is nothing else than a text file.

To make Python execute that program, there are hundreds of ways. In windows, simply right-click your file, open it with Python, and execute it. But you can also execute it from the Python interpreter itself. For this, the interpreter must know where your .py program is. In FreeCAD, the easiest way is to place your program in a place that FreeCAD's Python interpreter knows by default, such as FreeCAD's bin folder, or any of the Mod folders. (In Linux, you probably have a directory /home/<username>/.FreeCAD/Mod, let's add a subdirectory to that called scripts where we will put the text file.) Suppose we write a file like this:

def sum(a,b):
    return a + b

print "myTest.py succesfully loaded"

and we save it as myTest.py in our FreeCAD/bin directory (or on Linux to /home/<username>/.FreeCAD/Mod/scripts.) Now, let's start FreeCAD, and in the interpreter window, write:

import myTest

sans l'extension .py.

Le contenu du fichier sera tout simplement exécuté, ligne par ligne, comme si nous l'avions écrit dans l'interpréteur. La fonction somme a été créée, et le message "test.py a bien été chargé" sera affiché. Il ya une grande différence: la commande import est faite non seulement pour exécuter des programmes écrits dans des fichiers comme le nôtre, mais aussi de charger des fonctions dans Python, de sorte qu'elles deviennent disponibles dans l'interpréteur. Les fichiers contenant des fonctions, comme le nôtre, sont appelés modules.

Normalement, lorsque nous écrivons une fonction sum() dans l'interpréteur, nous l'exécutons simplement comme ceci,

sum(14,45)

comme nous l'avons fait plus haut.

Mais quand nous importons un module contenant une fonction comme sum(a,b), la syntaxe est un peu différente. Nous ferons:

myTest.sum(14,45)

That is, the module is imported as a "container", and all its functions are inside. This is extremely useful, because we can import a lot of modules, and keep everything well organized. So, basically, everywhere you see something.somethingElse, with a dot in between, that means somethingElse is inside something.

We can also import our sum() function directly into the main interpreter space, like this:

from myTest import *
sum(12,54)

Basically all modules behave like that. You import a module, then you can use its functions: module.function(argument). Almost all modules do that: they define functions, new data types and classes that you can use in the interpreter or in your own Python modules, because nothing prevents you from importing other modules inside your module!

Encore une chose extrêmement utile. Comment connaître les modules disponibles ? quelles sont les fonctions contenues dans ces modules et comment les utiliser (c'est à dire quels arguments sont demandés par la fonction)? Nous avons vu que Python a une fonction d'aide().

Alors, dans l'interpréteur Python de FreeCad faisons:

help()
modules

Will give us a list of all available modules. We can now type q to get out of the interactive help, and import any of them. We can even browse their content with the dir() command

import math
dir(math)

Nous voyons maintenant toutes les fonctions contenues dans le module math, ainsi que des trucs étranges comme: __ doc__, __ FILE__, __ name__ . . . .
Le __ doc__ est extrêmement utile, il s'agit d'un texte de documentation. Dans les modules, chaque fonction de fait a une __ doc__ qui explique comment l'utiliser. Par exemple, nous voyons qu'il ya une fonction sin dans le module math.
Vous voulez savoir comment utiliser cette fonction ? alors:

print math.sin.__doc__

(It may not be evident, but on either side of doc are two underscore characters.)

And finally one last little goodie: When we work on a new or existing module, it's best to replace the file extension with py such as: myModule.FCMacro => myModule.py. We often want to test it so we will load it as above.

import myModule
myModule.myTestFunction()

But what if we see that myTestFunction() doesn't work correctly? We go back to our editor and make changes. Then, instead of closing and reopening the python interpreter, we can simply update the module like this:

reload(myModule)

This file renaming is because Python doesn't know about the extension FCMacro.

However, there are two alternates: Inside the one macro use Python's exec or execfile functions.

f = open("myModule","r")
d = f.read()
exec d

ou

execfile "myModule"

To share code across macros, you can access the FreeCAD or FreeCADGui module (or any other Python module) and set any attribute to it. This should survive the execution of the macro.

import FreeCAD
if hasattr(FreeCAD,"macro2_executed"):
    ...
else:
    FreeCAD.macro2_executed = True # you can assign any value because we only check for the existence of the attribute
    ... execute macro2

Démarrer avec FreeCAD

Well, I think you now have a good idea of how Python works, and you can start exploring what FreeCAD has to offer. FreeCAD's Python functions are all well organized in different modules. Some of them are already loaded (imported) when you start FreeCAD. So, just do

dir()

et lire dans l’interpréteur tous les modules chargés dans FreeCad, voir Scripts de base dans FreeCad...

Of course, we saw here only a very small part of the Python world. There are many important concepts that we didn't mention. There are three very important Python reference documents on the net:

Be sure to bookmark them!