issue145:python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
issue145:python [2019/06/07 07:37] – d52fr | issue145:python [2019/06/11 11:21] (Version actuelle) – auntiee | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
**There are times when you need a number of variables initialized at startup based on the last time the program ran. In the world of Windows, this is usually saved in a configuration file with a " | **There are times when you need a number of variables initialized at startup based on the last time the program ran. In the world of Windows, this is usually saved in a configuration file with a " | ||
+ | |||
+ | Il y a des fois où vous avez besoin qu'un certain nombre de variables soient initialisées au démarrage en vous basant sur la dernière fois où le programme a tourné. Dans le monde de Windows, c'est en général enregistré dans un fichier de configuration avec l' | ||
**Installation | **Installation | ||
Ligne 14: | Ligne 16: | ||
import configparser** | import configparser** | ||
+ | |||
+ | Installation | ||
+ | |||
+ | La bibliothèque est configparser, | ||
+ | |||
+ | pip3 install configparser | ||
+ | |||
+ | Notez que j'ai utilisé pip3 plutôt que pip. Si vous utilisez toujours Python 2, vous devrez utiliser pip, mais, comme Python 2.x arrivera en fin de vie le 1er janvier 2020, j'ai décidé de n' | ||
+ | |||
+ | from backports import configparser | ||
+ | |||
+ | Autrement, vous l' | ||
+ | |||
+ | import configparser | ||
**Use | **Use | ||
Ligne 20: | Ligne 36: | ||
A very gross idea for the layout of the .ini file would be something like this...** | A very gross idea for the layout of the .ini file would be something like this...** | ||
+ | |||
+ | Utilisation | ||
+ | |||
+ | Le fichier INI (qui n'est PAS compatible avec le format de fichier « officiel » .ini de Windows) est un simple fichier texte. Vous pouvez utiliser l' | ||
+ | |||
+ | Une idée très grossière de la disposition du fichier .ini pourrait être quelque chose comme ceci : | ||
**[Animals] | **[Animals] | ||
Ligne 38: | Ligne 60: | ||
The library doesn' | The library doesn' | ||
+ | |||
+ | [Animals] # Animaux | ||
+ | animal1 = Frog # Grenouille | ||
+ | animal2 = Dog # Chien | ||
+ | animal3 = Hog # Porc | ||
+ | |||
+ | [Trees] # Arbres | ||
+ | tree1 = The Larch # Mélèze | ||
+ | tree2 = Elm # Orme | ||
+ | tree3 = Ash # Frêne | ||
+ | |||
+ | Dans cet exemple, nous avons deux sections, « Animals » et « Trees ». Chaque section contient trois variables (animal1, animal 2, etc.) qui sont nos clés et chacune a une valeur. Vous pouvez aussi définir une clé sans valeur par défaut : | ||
+ | |||
+ | tree4 = | ||
+ | |||
+ | Cependant, quand vous utilisez la variable « tree4 », c'est une chaîne vierge, et pas None (rien). | ||
+ | |||
+ | La bibliothèque n' | ||
**The Code | **The Code | ||
Ligne 47: | Ligne 87: | ||
In this simple demo program, we only need two imports, os and configparser. You'll see why we want the os library in a moment. Now we will define a global variable " | In this simple demo program, we only need two imports, os and configparser. You'll see why we want the os library in a moment. Now we will define a global variable " | ||
+ | |||
+ | Le code | ||
+ | |||
+ | Maintenant, nous allons rentrer dans le code que nous utiliserons pour lire, écrire et créer un fichier INI par défaut. Nous nommerons ce programme « iniFile.py ». Nous commencerons avec la section imports : | ||
+ | |||
+ | import os | ||
+ | import configparser | ||
+ | |||
+ | Dans ce simple programme de démo, nous n' | ||
**global iniFileName | **global iniFileName | ||
Ligne 59: | Ligne 108: | ||
global animal1, animal2, animal3 | global animal1, animal2, animal3 | ||
global theanswer** | global theanswer** | ||
+ | | ||
+ | global iniFileName | ||
+ | |||
+ | iniFileName = " | ||
+ | |||
+ | Maintenant, nous créerons une fonction pour lire notre fichier ini : | ||
+ | |||
+ | def read_ini(): | ||
+ | global ini, iniFileName | ||
+ | global tree1, tree2, tree3, tree4 | ||
+ | global animal1, animal2, animal3 | ||
+ | global theanswer | ||
**We define a number of global variables just to make things easy. Then, we check to see if the file exists (the os.path.isfile() method), and then read the file: | **We define a number of global variables just to make things easy. Then, we check to see if the file exists (the os.path.isfile() method), and then read the file: | ||
Ligne 67: | Ligne 128: | ||
This next bit of code (top right) shows how we can view the various sections and key/value sets.** | This next bit of code (top right) shows how we can view the various sections and key/value sets.** | ||
+ | |||
+ | Nous définissons un certain nombre de variables globales pour faciliter les choses. Ensuite, nous vérifions pour voir si le fichier existe (la méthode os.path.isfile()), | ||
+ | |||
+ | if os.path.isfile(iniFileName): | ||
+ | | ||
+ | ini.read(iniFileName) | ||
+ | |||
+ | Le prochain morceau de code (en haut à droite) montre comment nous pouvons voir les diverses sections et les ensembles clé/ | ||
**Now we can assign the values to the proper variables: | **Now we can assign the values to the proper variables: | ||
Ligne 84: | Ligne 153: | ||
theanswer = ans.get(' | theanswer = ans.get(' | ||
+ | | ||
+ | Maintenant, nous pouvons assigner les valeurs aux variables appropriées : | ||
+ | | ||
+ | animals = ini[' | ||
+ | animal1 = animals[' | ||
+ | animal2 = animals[' | ||
+ | animal3 = animals[' | ||
+ | trees = ini[' | ||
+ | tree1 = trees[' | ||
+ | tree2 = trees[' | ||
+ | tree3 = trees[' | ||
+ | tree4 = trees[' | ||
+ | ans = ini[' | ||
+ | |||
+ | Nous pouvons aussi utiliser la méthode .get de l' | ||
+ | |||
+ | theanswer = ans.get(' | ||
**Now, we return ' | **Now, we return ' | ||
Ligne 91: | Ligne 177: | ||
write_default_ini() | write_default_ini() | ||
return(False)** | return(False)** | ||
+ | | ||
+ | Maintenant, nous retournons « True » (vrai) lors d'un appel pour dire que le fichier INI existe. Sinon, comme le fichier INI n' | ||
+ | |||
+ | return(True) | ||
+ | else: | ||
+ | write_default_ini() | ||
+ | return(False) | ||
**Now, here is the function that can write to the INI file. In this case, we'll only write one value, but this will show how to do it. Basically, we use the .set(section, | **Now, here is the function that can write to the INI file. In this case, we'll only write one value, but this will show how to do it. Basically, we use the .set(section, | ||
Ligne 100: | Ligne 193: | ||
Here (bottom right) is the function to write a default INI file, just in case it doesn' | Here (bottom right) is the function to write a default INI file, just in case it doesn' | ||
+ | |||
+ | Voici maintenant la fonction qui peut lire le fichier INI. Dans notre cas, nous n' | ||
+ | |||
+ | def write_ini(): | ||
+ | global ini, iniFileName | ||
+ | ini.set(' | ||
+ | ini.write(open(iniFileName, | ||
+ | | ||
+ | Voici (en bas à droite) la fonction pour écrire un fichier INI par défaut, juste dans le cas où il n' | ||
**Finally, we write our configuration file to disk, using the global iniFileName that we set up earlier at the top of the program: | **Finally, we write our configuration file to disk, using the global iniFileName that we set up earlier at the top of the program: | ||
Ligne 111: | Ligne 213: | ||
The function init() (next page, bottom right) is where the real work is done; we instantiate the config parser object as ' | The function init() (next page, bottom right) is where the real work is done; we instantiate the config parser object as ' | ||
- | **Finally, we have our "if __name__" | + | Enfin, nous écrivons notre fichier |
+ | |||
+ | # Writing our configuration file | ||
+ | with open(iniFileName, | ||
+ | config.write(configfile) | ||
+ | |||
+ | Cette fonction (page suivante, en haut à droite) est utilisée pour afficher toutes les variables qui ont été tirées du fichier INI. | ||
+ | |||
+ | C'est dans la fonction init() (page suivante, en bas à droite) que tout le travail effectif s' | ||
+ | |||
+ | **Finally, we have our "if __name__" | ||
if __name__ == ' | if __name__ == ' | ||
Ligne 121: | Ligne 233: | ||
print(' | print(' | ||
- | That's all there is to it. Here's what the output looks like the first time the program is run:** | + | That's all there is to it. Here's what the output looks like the first time the program is run: |
- | **[' | + | [' |
Section: Animals | Section: Animals | ||
Key = animal1 - Value = Frog | Key = animal1 - Value = Frog | ||
Ligne 140: | Ligne 252: | ||
theanswer type is <class ' | theanswer type is <class ' | ||
Program End** | Program End** | ||
+ | |||
+ | Enfin, nous avons notre point d' | ||
+ | |||
+ | if __name__ == ' | ||
+ | # ========================== | ||
+ | # All code is run from the init() function | ||
+ | # ========================== | ||
+ | init() | ||
+ | # Notify user that we are done | ||
+ | print(' | ||
+ | | ||
+ | C'est tout ce qu'il y a dire là-dessus. Voici à quoi ressemble la sortie la première fois que le progamme tourne : | ||
+ | |||
+ | [' | ||
+ | Section: Animals | ||
+ | Key = animal1 - Value = Frog | ||
+ | Key = animal2 - Value = Dog | ||
+ | Key = animal3 - Value = Hog | ||
+ | Section: Trees | ||
+ | Key = tree1 - Value = The Larch | ||
+ | Key = tree2 - Value = Elm | ||
+ | Key = tree3 - Value = Ash | ||
+ | Key = tree4 - Value = | ||
+ | Section: Answers | ||
+ | Key = life, the universe and everything - Value = 42 | ||
+ | animal1: Frog, animal2: Dog, animal3: Hog | ||
+ | tree1: The Larch, tree2: Elm, tree3: Ash, tree4: | ||
+ | What's the answer to Life, The Universe and Everything? 42 | ||
+ | theanswer type is <class ' | ||
+ | Program End | ||
**Notice that the value for " | **Notice that the value for " | ||
Ligne 156: | Ligne 298: | ||
[Answers] | [Answers] | ||
life, the universe and everything = 42** | life, the universe and everything = 42** | ||
+ | |||
+ | Notez que la valeur de « tree4 » est vierge. Cependant, si vous regardez le fichier INI, il ressemble à ceci : | ||
+ | |||
+ | [Animals] | ||
+ | animal1 = Frog | ||
+ | animal2 = Dog | ||
+ | animal3 = Hog | ||
+ | |||
+ | [Trees] | ||
+ | tree1 = The Larch | ||
+ | tree2 = Elm | ||
+ | tree3 = Ash | ||
+ | tree4 = Birch | ||
+ | |||
+ | [Answers] | ||
+ | life, the universe and everything = 42 | ||
**That' | **That' | ||
Ligne 164: | Ligne 322: | ||
Until next time, keep coding and have a great month! ** | Until next time, keep coding and have a great month! ** | ||
+ | |||
+ | C'est parce que la dernière ligne de la fonction init() met à jour la variable « tree4 » avec la valeur Birch (bouleau) dans la fonction write_ini(). | ||
+ | |||
+ | Je n'ai pas cherché trop loin dans les possibilités de cette bibliothèque, | ||
+ | |||
+ | J'ai mis l' | ||
+ | |||
+ | Jusqu' | ||
issue145/python.1559885875.txt.gz · Dernière modification : 2019/06/07 07:37 de d52fr