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 19:26] – 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' | + | 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 19: | Ligne 19: | ||
Installation | Installation | ||
- | La bibliothèque est configparser, | + | La bibliothèque est configparser, |
pip3 install 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' utiliser désormais que la syntaxe de Python 3.x. La version actuelle est la 3.7.4 (d' | + | 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 | from backports import configparser | ||
- | Autrement, vous l' | + | Autrement, vous l' |
import configparser | import configparser | ||
Ligne 39: | Ligne 39: | ||
Utilisation | 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' | + | 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... | + | Une idée très grossière de la disposition du fichier .ini pourrait être quelque chose comme ceci : |
**[Animals] | **[Animals] | ||
Ligne 61: | Ligne 61: | ||
The library doesn' | The library doesn' | ||
- | [Animals] | + | [Animals] |
- | animal1 = Frog | + | animal1 = Frog # Grenouille |
- | animal2 = Dog | + | animal2 = Dog # Chien |
- | animal3 = Hog | + | animal3 = Hog # Porc |
- | [Trees] | + | [Trees] |
- | tree1 = The Larch | + | tree1 = The Larch # Mélèze |
- | tree2 = Elm | + | tree2 = Elm # Orme |
- | tree3 = Ash | + | 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 | + | 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 |
tree4 = | tree4 = | ||
Ligne 77: | Ligne 77: | ||
Cependant, quand vous utilisez la variable « tree4 », c'est une chaîne vierge, et pas None (rien). | Cependant, quand vous utilisez la variable « tree4 », c'est une chaîne vierge, et pas None (rien). | ||
- | La bibliothèque n' | + | La bibliothèque n' |
**The Code | **The Code | ||
Ligne 95: | Ligne 95: | ||
import configparser | import configparser | ||
- | Dans ce simple programme de démo, nous n' | + | Dans ce simple programme de démo, nous n' |
**global iniFileName | **global iniFileName | ||
Ligne 129: | Ligne 129: | ||
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 | + | 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()), puis nous lisons |
if os.path.isfile(iniFileName): | if os.path.isfile(iniFileName): | ||
Ligne 135: | Ligne 135: | ||
ini.read(iniFileName) | ini.read(iniFileName) | ||
- | Ce prochain morceau de code (en haut à droite) montre comment nous pouvons voir les diverses sections et les ensembles clé/ | + | 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 153: | 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 160: | 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 169: | 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 180: | 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 190: | 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 209: | 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 225: | 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 233: | 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.1559928371.txt.gz · Dernière modification : 2019/06/07 19:26 de d52fr