issue145:python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
issue145:python [2019/06/01 14:54] – créée auntiee | 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 " |
- | Installation | + | 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 | ||
The library is configparser, | The library is configparser, | ||
Ligne 12: | Ligne 14: | ||
Otherwise, you would import it as normal: | Otherwise, you would import it as normal: | ||
+ | |||
+ | 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 | import configparser | ||
- | Use | + | **Use |
The INI file (which is NOT compatible with Windows " | The INI file (which is NOT compatible with Windows " | ||
- | 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...** |
- | [Animals] | + | 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] | ||
animal1 = Frog | animal1 = Frog | ||
animal2 = Dog | animal2 = Dog | ||
Ligne 37: | Ligne 59: | ||
However, when you use the ' | However, when you use the ' | ||
- | 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 |
Now we'll get into the code that we would use to read, write and create a default INI file. We'll name this program " | Now we'll get into the code that we would use to read, write and create a default INI file. We'll name this program " | ||
Ligne 46: | Ligne 86: | ||
import configparser | import configparser | ||
- | 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 " |
- | global iniFileName | + | 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 | ||
iniFileName = " | iniFileName = " | ||
Now, we'll create a function to read our ini file: | Now, we'll create a function to read our ini file: | ||
+ | |||
+ | def read_ini(): | ||
+ | global ini, iniFileName | ||
+ | global tree1, tree2, tree3, tree4 | ||
+ | global animal1, animal2, animal3 | ||
+ | global theanswer** | ||
+ | | ||
+ | global iniFileName | ||
+ | |||
+ | iniFileName = " | ||
+ | |||
+ | Maintenant, nous créerons une fonction pour lire notre fichier ini : | ||
def read_ini(): | def read_ini(): | ||
Ligne 60: | Ligne 121: | ||
global theanswer | 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: |
if os.path.isfile(iniFileName): | if os.path.isfile(iniFileName): | ||
Ligne 66: | Ligne 127: | ||
ini.read(iniFileName) | ini.read(iniFileName) | ||
- | 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.** |
- | Now we can assign the values to the proper variables: | + | 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: | ||
animals = ini[' | animals = ini[' | ||
Ligne 82: | Ligne 151: | ||
We can also use the .get method of the section object to assign the value to a variable: | We can also use the .get method of the section object to assign the value to a variable: | ||
+ | |||
+ | 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(' | theanswer = ans.get(' | ||
- | Now, we return ' | + | **Now, we return ' |
+ | |||
+ | return(True) | ||
+ | else: | ||
+ | write_default_ini() | ||
+ | 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) | return(True) | ||
Ligne 92: | Ligne 185: | ||
return(False) | 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, |
def write_ini(): | def write_ini(): | ||
Ligne 99: | Ligne 192: | ||
ini.write(open(iniFileName, | ini.write(open(iniFileName, | ||
- | 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: |
# Writing our configuration file | # Writing our configuration file | ||
Ligne 109: | Ligne 211: | ||
This function (next page, top right) simply is used to display all the variables that were pulled from the INI file: | This function (next page, top right) simply is used to display all the variables that were pulled from the INI file: | ||
- | 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 122: | Ligne 234: | ||
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 | ||
+ | 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** | ||
+ | |||
+ | 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 : | ||
[' | [' | ||
Ligne 141: | Ligne 283: | ||
Program End | Program End | ||
- | Notice that the value for " | + | **Notice that the value for " |
+ | |||
+ | [Animals] | ||
+ | animal1 = Frog | ||
+ | animal2 = Dog | ||
+ | animal3 = Hog | ||
+ | |||
+ | [Trees] | ||
+ | tree1 = The Larch | ||
+ | tree2 = Elm | ||
+ | tree3 = Ash | ||
+ | tree4 = Birch | ||
+ | |||
+ | [Answers] | ||
+ | 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] | [Animals] | ||
Ligne 157: | Ligne 315: | ||
life, the universe and everything = 42 | life, the universe and everything = 42 | ||
- | That's because the last line of the init() function updates the " | + | **That's because the last line of the init() function updates the " |
I didn't get too deep into the possibilities of this library, but if you want to learn more, you can read about it from the official Python docs on configparser at https:// | I didn't get too deep into the possibilities of this library, but if you want to learn more, you can read about it from the official Python docs on configparser at https:// | ||
Ligne 163: | Ligne 321: | ||
I've put the code example for this month on pastebin at https:// | I've put the code example for this month on pastebin at https:// | ||
- | 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.1559393690.txt.gz · Dernière modification : 2019/06/01 14:54 de auntiee