Outils pour utilisateurs

Outils du site


issue189:python

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
issue189:python [2023/01/30 07:38] d52frissue189:python [2023/02/02 10:25] (Version actuelle) auntiee
Ligne 8: Ligne 8:
  
 To get started, let's assume that I created a Python program that used PAGE to create the GUI front end. Let's further assume that I want to give the user the ability to select the Theme for the program (since it uses ttk Widgets). I want the program to remember what that user decided for their theme of choice. To do this, I will use a configuration file to keep all the customization information.** To get started, let's assume that I created a Python program that used PAGE to create the GUI front end. Let's further assume that I want to give the user the ability to select the Theme for the program (since it uses ttk Widgets). I want the program to remember what that user decided for their theme of choice. To do this, I will use a configuration file to keep all the customization information.**
 +
 +Python 3.11.1 est maintenant disponible (à partir du 6 décembre 2022) et, comme d'habitude, il apporte un certain nombre de changements et d'améliorations. Si vous voulez savoir ce qu'il y a de nouveau dans la version 3.11.1, vous pouvez vous rendre sur le site https://docs.python.org/3/whatsnew/3.11.html pour trouver toutes les informations.
 +
 +L'une des nouveautés de la version 3.11.1 est un nouveau module de la bibliothèque standard appelé tomllib, qui offre un « support » pour l'analyse des documents de style TOML. Remarquez que j'ai dit « support ». Ce n'est pas un support complet, mais c'est un support. Je vais en parler davantage dans quelques instants.
 +
 +Qu'est-ce que TOML ?
 +
 +TOML est l'acronyme de Tom's Obvious Minimal Language et, d'après ce que j'ai compris, il a été créé principalement comme un moyen de stocker des données de configuration. Beaucoup d'autres moyens de stocker des données de configuration ne permettent pas d'enregistrer des commentaires en ligne.
 +
 +Pour commencer, supposons que j'ai créé un programme Python qui utilise PAGE pour créer l'interface utilisateur graphique. Supposons également que je veuille donner à l'utilisateur la possibilité de sélectionner le thème du programme (puisqu'il utilise des Widgets ttk). Je veux que le programme se souvienne de ce que l'utilisateur a décidé pour le thème choisi. Pour ce faire, je vais utiliser un fichier de configuration pour conserver toutes les informations de personnalisation.
 +
  
 **Shown top right is a simplified version of the hypothetical configuration file. **Shown top right is a simplified version of the hypothetical configuration file.
Ligne 27: Ligne 38:
  
 Using pretty print, we can now look at the data that was brought in from the config file (next page, top right).** Using pretty print, we can now look at the data that was brought in from the config file (next page, top right).**
 +
 +En haut à droite, vous voyez une version simplifiée du fichier de configuration hypothétique.
 +
 +À ce stade, il ressemble à un fichier de configuration standard que l'on peut trouver à peu près partout. Cependant, s'il s'agissait d'un fichier de configuration « standard » de type configparser, la première entrée de la section [Themes] ne serait pas possible directement, puisque configparser ne supporte pas les listes sans manipulation. En TOML, les sections sont appelées tables. La clé available_themes a la valeur d'un tableau. Une fois portée en Python, elle devient une liste.
 +
 +Voyons maintenant comment introduire les données dans un programme.
 +
 +Bien sûr, nous devons importer la bibliothèque tomllib. Rappelez-vous que celle-ci n'est prise en charge directement que sous Python 3.11.
 +
 +import tomllib
 +import pprint
 +
 +Ensuite, nous ouvrons le fichier de configuration et utilisons la méthode load de la bibliothèque.
 +
 +with open("config.toml", "rb") as f:
 +   
 +data = tomllib.load(f)
 +
 +En utilisant pretty print, nous pouvons maintenant regarder les données qui ont été apportées par le fichier de configuration (page suivante, en haut à droite).
  
 **You can see that it is simply just a dictionary. To access the data, we do it just like any other dictionary (next page, bottom left). **You can see that it is simply just a dictionary. To access the data, we do it just like any other dictionary (next page, bottom left).
Ligne 38: Ligne 68:
  
 The Python tomllib library provides only two functions, tomllib.loads which loads a TOML string and returns a dictionary, and tomllib.load which reads a TOML file and returns again, a dictionary. See https://docs.python.org/3/library/tomllib.html.** The Python tomllib library provides only two functions, tomllib.loads which loads a TOML string and returns a dictionary, and tomllib.load which reads a TOML file and returns again, a dictionary. See https://docs.python.org/3/library/tomllib.html.**
 +
 +Vous pouvez voir qu'il s'agit simplement d'un dictionnaire. Pour accéder aux données, nous procédons comme pour tout autre dictionnaire (page suivante, en bas à gauche).
 +
 +Le résultat de notre petit programme ressemblera à ceci :
 +
 +Available Themes: ['notsodark', 'plastik', 'waldorf', 'page_wheat', 'clearlooks', 'forest-light', 'forest-dark', 'default', 'clam', 'classic', 'alt']
 +Your default Theme is: waldorf
 +Your current Theme is: notsodark
 +Program version 0.7.1
 +
 +La bibliothèque Python tomllib ne fournit que deux fonctions, tomllib.loads qui charge une chaîne TOML et retourne un dictionnaire, et tomllib.load qui lit un fichier TOML et retourne à nouveau un dictionnaire. Voir https://docs.python.org/3/library/tomllib.html.
 +
  
 **Unfortunately, Python does not provide any way to properly write out the TOML data. The good news is that there is a third party library called tomli_w which will allow you to write the TOML data back to a file. So if the user decides to change his current theme from 'notsodark' to 'clam', it's a simple chore to make the change and write it back. You can install it via pip. **Unfortunately, Python does not provide any way to properly write out the TOML data. The good news is that there is a third party library called tomli_w which will allow you to write the TOML data back to a file. So if the user decides to change his current theme from 'notsodark' to 'clam', it's a simple chore to make the change and write it back. You can install it via pip.
Ligne 58: Ligne 100:
 The home pages for tomli-w and tomli can be found at https://github.com/hukkin/tomli-w** The home pages for tomli-w and tomli can be found at https://github.com/hukkin/tomli-w**
  
 +Malheureusement, Python ne fournit aucun moyen d'écrire correctement les données TOML. La bonne nouvelle est qu'il existe une bibliothèque tierce appelée tomli_w qui vous permet de réécrire les données TOML dans un fichier. Ainsi, si l'utilisateur décide de changer son thème actuel de « notsodark » à « clam », il lui suffira d'effectuer le changement et de le réécrire. Vous pouvez l'installer via pip.
  
 +pip install tomli-w
 +
 +Une fois qu'il est installé, vous pouvez simplement l'écrire comme un fichier normal, mais binaire.
 +
 +Rappelez-vous que le tomllib (en bas à droite) n'est livré qu'avec Python 3.11. Alors que faire si vous utilisez Python 3.8.10 et que vous n'êtes pas encore prêt à faire la mise à niveau ? N'ayez crainte. La bibliothèque tomli-w est actuellement supportée dans les versions 3.7 jusqu'à 3.11. Pour obtenir l'analyseur analogue à tomllib, vous pouvez installer tomli. Encore une fois, il suffit d'utiliser pip.
 +
 +pip install tomli
 +
 +Bien sûr, si vous utilisez tomli plutôt que tomllib, vous devez faire l'importation un peu différemment.
 +
 +#import tomllib
 +import tomli
 +import tomli_w
 +import pprint
 +
 +Les pages d'accueil de tomli-w et de tomli se trouvent aux adresses :
 +https://github.com/hukkin/tomli-w
 +
 +et
  
 **https://github.com/hukkin/tomli **https://github.com/hukkin/tomli
Ligne 71: Ligne 133:
  
 Until next time, as always; stay safe, healthy, positive and creative!** Until next time, as always; stay safe, healthy, positive and creative!**
 +
 +https://github.com/hukkin/tomli
 +
 +Si vous souhaitez consulter les informations complètes sur TOML, vous pouvez visiter la page d'accueil à l'adresse https://toml.io/en/
 +
 +Il existe un autre paquet tiers TOML pour Python à l'adresse https://github.com/sdispater/tomlkit . Sa documentation se trouve à l'adresse https://github.com/sdispater/tomlkit/blob/master/docs/quickstart.rst. Je n'ai pas encore eu l'occasion de jouer avec, mais il semble prometteur.
 +
 +J'ai placé le fichier config.toml et le fichier Python (toml1.py) dans mon dépôt à https://github.com/gregwa1953/FCM-189.
 +
 +C'est tout pour ce mois-ci. Bonne année ! !!
 +
 +Jusqu'à la prochaine fois, comme toujours, restez en sécurité, en bonne santé, positif et créatif !
  
issue189/python.1675060729.txt.gz · Dernière modification : 2023/01/30 07:38 de d52fr