issue152: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 | ||
| issue152:python [2020/01/03 10:03] – d52fr | issue152:python [2020/01/04 14:34] (Version actuelle) – auntiee | ||
|---|---|---|---|
| Ligne 5: | Ligne 5: | ||
| One thing that I've found is that when you need to (or want to) save some of the data in the middle of a process, often the pickle library is used. I've known about pickle for a long time, but have really never messed with it much, so I thought I'd explore some.** | One thing that I've found is that when you need to (or want to) save some of the data in the middle of a process, often the pickle library is used. I've known about pickle for a long time, but have really never messed with it much, so I thought I'd explore some.** | ||
| - | Dernièrement, | + | Dernièrement, |
| Voulez-vous des cornichons avec ? | Voulez-vous des cornichons avec ? | ||
| - | Une chose que j' | + | Une chose que j' |
| **Pickle or olive? | **Pickle or olive? | ||
| Ligne 19: | Ligne 19: | ||
| Cornichon ou olive ? | Cornichon ou olive ? | ||
| - | Une olive est un élément merveilleux dans le martini. Elle ne fait rien pour le code Python. C'est, cependant, une variété non vénimeuse | + | Une olive est un élément merveilleux dans le martini. Elle ne fait rien pour le code Python. C'est, cependant, une variété non venimeuse |
| - | D'un autre côté, pickle est un eméthode | + | En revanche, pickle est une méthode |
| **Serializing means to take an object from memory, convert it into a stream of bytes that can be stored on disk. De-serializing is the reverse of the process. Let's say you have a dictionary. You can't just dump it to disk from memory. You have to convert it into a format that lends itself to being a disk file. JSON, XML, HTML all jump to mind. Pickles are just another way to do this. There' | **Serializing means to take an object from memory, convert it into a stream of bytes that can be stored on disk. De-serializing is the reverse of the process. Let's say you have a dictionary. You can't just dump it to disk from memory. You have to convert it into a format that lends itself to being a disk file. JSON, XML, HTML all jump to mind. Pickles are just another way to do this. There' | ||
| Ligne 27: | Ligne 27: | ||
| What can you pickle? Well most Python objects can be pickled, but there are a few that can't. While you can pickle simple objects (Integers, floats, complex numbers and strings), you normally would pickle Tuples, Lists, sets and Dictionaries that are built from most objects. However, things like generators, lambda functions and defaultdicts can not be pickled. There are some workarounds, | What can you pickle? Well most Python objects can be pickled, but there are a few that can't. While you can pickle simple objects (Integers, floats, complex numbers and strings), you normally would pickle Tuples, Lists, sets and Dictionaries that are built from most objects. However, things like generators, lambda functions and defaultdicts can not be pickled. There are some workarounds, | ||
| - | « Sérialiser » signifie prendre un objet en mémoire et le convertir en un flux de bits que vous pouvez sauvegarder sur disque. Dé-sérialiser est le processus inverse. Disons que nous avons un dictionnaire. Vous ne pouvez pas le passer en bloc de la mémoire au disque. Vous devez le convertir dans un format qui l'améne | + | « Sérialiser » signifie prendre un objet en mémoire et le convertir en un flux de bits que vous pouvez sauvegarder sur disque. Dé-sérialiser est le processus inverse. Disons que nous avons un dictionnaire. Vous ne pouvez pas le passer en bloc de la mémoire au disque. Vous devez le convertir dans un format qui l'amène |
| - | Qu' | + | Qu' |
| **Pickling Process | **Pickling Process | ||
| Ligne 41: | Ligne 41: | ||
| Processus pour « pickler » | Processus pour « pickler » | ||
| - | Je veux remercier mon ami norvégien Halvard Tislavoll pour l' | + | Je veux remercier mon ami norvégien Halvard Tislavoll pour l' |
| - | Disons que vous voulez créer un jeu de couleurs qui pourraient être utilisées pour créer une interface utilisateur graphique (GUI). Tkinter (comme d' | + | Disons que vous voulez créer un jeu de couleurs qui pourraient être utilisées pour créer une interface utilisateur graphique (GUI). Tkinter (comme d' |
| - | Sous Ubuntu, il existe un fichier situé dans le dossier /etc/x11, appelé rgb.txt. Faites-en une copie et mettez-la dans votre dossier de travail. | + | Sous Ubuntu, il existe un fichier situé dans le dossier /etc/x11, appelé rgb.txt. Faites-en une copie et mettez-le dans votre dossier de travail. |
| **Please note that Halvard' | **Please note that Halvard' | ||
| Ligne 58: | Ligne 58: | ||
| myDict = {}** | myDict = {}** | ||
| - | Notez, s'il vous plait, que le style de codage de Halvard n'est pas le même que le mien et je suis sûr qu'il n'est pas le même que le votre. Cependant, je suis sûr que vous saurez comprendre son code. | + | Notez, s'il vous plaît, que le style de codage de Halvard n'est pas le même que le mien et je suis sûr qu'il n'est pas le même que le vôtre. Cependant, je suis sûr que vous saurez comprendre son code. |
| - | Maintenant, nous pouvons commencer à créer un programme pour convertir ce texte en dictionnaire puis le traiter avec pickle. Nommez « rgb2pickle.py » votre fichier de programme. D' | + | Maintenant, nous pouvons commencer à créer un programme pour convertir ce texte en dictionnaire, puis le traiter avec pickle. Nommez |
| import pickle | import pickle | ||
| - | Maintenant, définissons une liste vide et un dictionnaire vide... | + | Maintenant, définissons une liste vide et un dictionnaire vide : |
| myList = [] | myList = [] | ||
| Ligne 74: | Ligne 74: | ||
| This function takes the list and puts everything into a dictionary... | This function takes the list and puts everything into a dictionary... | ||
| - | |||
| def txt2dict(myList): | def txt2dict(myList): | ||
| Ligne 91: | Ligne 90: | ||
| B = item[8: | B = item[8: | ||
| B = emptystring(B)** | B = emptystring(B)** | ||
| + | | ||
| + | Ensuite, nous créerons quelques fonctions support. D' | ||
| + | |||
| + | Cette fonction prend la liste et met tout dans un dictionnaire : | ||
| + | |||
| + | def txt2dict(myList): | ||
| + | i = 0 | ||
| + | aDict = {} | ||
| + | for item in myList: | ||
| + | newList = [] | ||
| + | # pick name, clean it for tab | ||
| + | name = item[13: | ||
| + | name = name.rstrip() | ||
| + | # pick RGB values (dec) | ||
| + | R = item[0: | ||
| + | R = emptystring(R) | ||
| + | G = item[4: | ||
| + | G = emptystring(G) | ||
| + | B = item[8: | ||
| + | B = emptystring(B) | ||
| **Now, convert the RGB values to a hex value… | **Now, convert the RGB values to a hex value… | ||
| Ligne 112: | Ligne 131: | ||
| i += 1 | i += 1 | ||
| return aDict** | return aDict** | ||
| + | | ||
| + | Maintenant, convertissons les valeurs RGB en valeur hexadécimale : | ||
| + | | ||
| + | # convertir la valeur dec2hex | ||
| + | H1 = dec2hex(R) | ||
| + | H2 = dec2hex(G) | ||
| + | H3 = dec2hex(B) | ||
| + | # contruire la valeur en # | ||
| + | H = f"# | ||
| + | |||
| + | Et rajoutons cela à la structure en liste et mettons à jour le dictionnaire : | ||
| + | |||
| + | # faire une liste avec une nouvelle structure en colonnes | ||
| + | newList.append(name) | ||
| + | newList.append(R) | ||
| + | newList.append(G) | ||
| + | newList.append(B) | ||
| + | newList.append(H) | ||
| + | aDict[i] = newList | ||
| + | i += 1 | ||
| + | return aDict | ||
| **Now that all of the helper functions are done, let's put them all together (next page, top right). | **Now that all of the helper functions are done, let's put them all together (next page, top right). | ||
| The terminal output is very uninteresting and responds very quickly. Now, we have a pickle file, what do we do with it? | The terminal output is very uninteresting and responds very quickly. Now, we have a pickle file, what do we do with it? | ||
| + | |||
| Depickling a pickle | Depickling a pickle | ||
| Ligne 124: | Ligne 165: | ||
| with open(filename, | with open(filename, | ||
| data = pkl.load(f)** | data = pkl.load(f)** | ||
| + | |||
| + | Maintenant que toutes les fonctions d'aide sont faites, rassemblons-les (page suivante, en haut à droite). | ||
| + | |||
| + | La sortie sur le terminal est très intéressante et répond très rapidement. Maintenant nous avons un fichier pickle ; que faire avec lui ? | ||
| + | |||
| + | « Dé-pickler » un pickle | ||
| + | |||
| + | Dé-pickler (ou dé-sérialiser) est tout aussi facile que de créer le fichier pickle une fois que vos données sont prêtes. | ||
| + | |||
| + | Voici un rapide bout de code que nous pouvons utiliser dans une appli en ligne de commande : | ||
| + | |||
| + | with open(filename, | ||
| + | data = pkl.load(f) | ||
| **This works well only if the pickle file was created with Python 3. If, however, it was created with Python 2 and the cPickle routine, it will probably error out. An easy workaround for this is (shown bottom right). | **This works well only if the pickle file was created with Python 3. If, however, it was created with Python 2 and the cPickle routine, it will probably error out. An easy workaround for this is (shown bottom right). | ||
| Ligne 130: | Ligne 184: | ||
| I won’t bore you with the details of how to do this in Page, since there’s only three buttons, an entry widget, two labels, and a scrolled text widget. We’ve already covered that. However, I will show you the code that is important in the _support file. I really didn’t worry about any error checking for the simple project.** | I won’t bore you with the details of how to do this in Page, since there’s only three buttons, an entry widget, two labels, and a scrolled text widget. We’ve already covered that. However, I will show you the code that is important in the _support file. I really didn’t worry about any error checking for the simple project.** | ||
| + | |||
| + | Ça marche bien seulement si le fichier pickle a été créé avec Python 3. Cependant, s'il a été créé avec Python 2 et la routine cPickle, il a des chances de sortir une erreur. Une solution de repli facile est (voir en bas à droite). | ||
| + | |||
| + | De toute manière, pour mes besoins, je voulais être capable en fait de voir les données sous une forme brute, directement depuis le fichier pickle. J'ai fait un rapide formulaire Page et y ai mis très peu de code (MERCI Page !) et voici le résultat : | ||
| + | |||
| + | Je ne vous ennuierai pas avec les détails de comment le faire dans Page, car il n'y a que trois boutons, un gadget de saisie, deux étiquettes et un gadget de liste déroulante. Nous en avons déjà parlé. Cependant, je vous montrerai le code qui est important dans le fichier _support. Je ne me suis préoccupé d' | ||
| **We’ll look at the callback for the “get filename” button (the one that has “...” as its text) first (middle right). Basically, this simply calls a tkinter askopenfilename filedialog and puts the selected filename and path into the entry widget for display. | **We’ll look at the callback for the “get filename” button (the one that has “...” as its text) first (middle right). Basically, this simply calls a tkinter askopenfilename filedialog and puts the selected filename and path into the entry widget for display. | ||
| Ligne 139: | Ligne 199: | ||
| • Determine the type of data structure and display it. | • Determine the type of data structure and display it. | ||
| • Fill the text widget with the data from the structure (if possible).** | • Fill the text widget with the data from the structure (if possible).** | ||
| + | |||
| + | Nous regarderons d' | ||
| + | |||
| + | Ensuite, vient la fonction de rappel pour le bouton « GO ». C'est ici que le vrai travail se fait. La logique est de : | ||
| + | ••Effacer le champ de texte. | ||
| + | ••Ouvrir le fichier que l' | ||
| + | ••Le dé-pickler | ||
| + | ••Déterminer le type de la structure de données et l' | ||
| + | ••Remplir le gadget de texte avec les données de la structure (si possible). | ||
| + | |||
| **def on_btnGo(): | **def on_btnGo(): | ||
| Ligne 154: | Ligne 224: | ||
| # Clear the ScrolledText Widget | # Clear the ScrolledText Widget | ||
| w.Scrolledtext1.delete(' | w.Scrolledtext1.delete(' | ||
| + | | ||
| + | def on_btnGo(): | ||
| + | # print(' | ||
| + | # sys.stdout.flush() | ||
| + | clear_stw() | ||
| + | |||
| + | Voici le vrai code pour dépickler (page suivante, en haut à droite). | ||
| + | |||
| + | Enfin, basé sur le type de données que nous avons, remplissez le gadget de texte (en bas à droite). | ||
| + | |||
| + | La fonction pour effacer le gadget de texte est vraiment simple : | ||
| + | |||
| + | def clear_stw(): | ||
| + | # Effacer le gadget ScrolledText | ||
| + | w.Scrolledtext1.delete(' | ||
| **And the very last thing, just to be complete, is the Page provided function that defines the tkinter variables that allow easy setting of the text for the various widgets. | **And the very last thing, just to be complete, is the Page provided function that defines the tkinter variables that allow easy setting of the text for the various widgets. | ||
| Ligne 165: | Ligne 250: | ||
| That’s it.** | That’s it.** | ||
| + | |||
| + | Et la toute dernière chose, juste pour être complet, est la fonction fournie par Page qui définit les variables tkinter qui permettent un paramétrage facile du texte pour les différents gadgets : | ||
| + | |||
| + | def set_Tk_var(): | ||
| + | global pickleType | ||
| + | pickleType = tk.StringVar() | ||
| + | pickleType.set('' | ||
| + | global entry_var | ||
| + | entry_var = tk.StringVar() | ||
| + | |||
| + | Et c'est tout. | ||
| **Here is a good website that can help you understand the pickling process if you still want to learn more... https:// | **Here is a good website that can help you understand the pickling process if you still want to learn more... https:// | ||
| Ligne 173: | Ligne 269: | ||
| Until next time, I hope you have a wonderful New Year and remember to keep coding!** | Until next time, I hope you have a wonderful New Year and remember to keep coding!** | ||
| + | |||
| + | Voici un bon site Web qui peut vous aider à comprendre le processus de pickling si vous voulez en apprendre plus...https:// | ||
| + | |||
| + | J'ai mis les fichiers source du fichier rgb2pickle.py venant de Halvard sur pastebin à : https:// | ||
| + | |||
| + | Et les sources Python pour le programme de dé-pickling en interface graphique sont aussi à : | ||
| + | Depickle.py - https:// | ||
| + | Depickle_support.py - https:// | ||
| + | |||
| + | En attendant la prochaine fois, je vous souhaite un merveilleux Nouvel An et n' | ||
issue152/python.1578042230.txt.gz · Dernière modification : 2020/01/03 10:03 de d52fr
