Outils pour utilisateurs

Outils du site


issue169:python

As usual, my mind and world has been preoccupied by other things, and my ‘Python in the REAL world’ (again, as usual) ended up being the to-do item falling to the bottom of the list. I’ve been SO focused on playing with the Microcontrollers and MicroPython that time has slipped by (again, as usual) and it’s now time for me to write the article for the Python side of things. So this month, I will show you how to use the bext library to control the screen in a terminal window, similar to the curses library, but this will also work on Microsoft Windows as well.

Comme d'habitude, mon esprit et le monde se préoccupaient d'autres choses et ma rubrique « Python dans le monde réel » (à nouveau, comme d'habitude) a fini par être celle des tâches qui est tombée jusqu'en bas de la liste. Je me suis TELLEMENT concentré sur les micro-contrôleurs et MicroPython, que le temps m'a échappé (à nouveau, comme d'habitude) et le moment est maintenant venu pour moi d'écrire l'article du côté de Python.

Ainsi, ce mois-ci, je vous montrerai comment utiliser la bibliothèque bext pour contrôler l'écran dans une fenêtre du terminal ; c'est similaire à la bibliothèque curses, mais cela fonctionnera également sur Microsoft Wndows.

What is bext? Bext, according to its homepag, is: “Basically, use Bext if you want to move the cursor around the terminal window and have colorful text, like some kind of limited curses module (but it works on Windows also.)” With more and more applications moving to a GUI model, use of “fancy” graphics inside a terminal window is getting more and more rare. However, there is still something to be said for the ability to easily control the cursor, placement of text, and even the color of text within a CLI program. To install bext, all you have to do is use pip (or pip3)… pip install bext Once you have bext installed, you can begin to use it. Let’s create a very simple program to show off its abilities.

Qu'est-ce que bext ?

D'après la page d'accueil de son site Web, on utilise Bext « si l'on veut pouvoir bouger le curseur dans la fenêtre du terminal et avoir du texte plein de couleurs, comme une sorte de module curses limité (mais il fonctionne aussi sous Windows) ».

Puisque de plus en plus d'applications passent à une interface graphique, l'utilisation d'un affichage graphique « raffiné » dans une fenêtre du terminal devient de plus en plus rare. Toutefois, il y a des choses à dire en faveur de la capacité de contrôler facilement le curseur, de bien placer le texte et même de colorier le texte à l'intérieur d'un programme en ligne de commande.

Pour installer bext, tout ce qu'il faut faire est d'utiliser pip (ou pip3) :

pip install bext

Une fois que bext est installée, vous pouvez commencer à l'utiliser. Créons un très simple programme pour mettre ses capacités en valeur.

Program project #1 First, a small warning about running projects that use bext in your IDE. Since bext controls a terminal positioning and colors, the terminal that your IDE uses might not work correctly. If you happen to use VS Code, the programs will work, but you need to remember to click in the terminal at the bottom of the Code window. If you are using Geany, it also will work, but the terminal window will most likely scroll beyond the actual program output. I haven’t tried IDLE, but I’m guessing that it won’t work. Therefore, create your program in your normal IDE, then open a terminal window to test your program from the command-line. Below is the code for our first bext program… As always, we need to import bext. Since the program won’t work without it, I use a try | except to wrap the import statement. That way, if it fails, the user knows why immediately. Next, we need to do some setup. We start by setting the background color (bext.bg()) and foreground color (bext.fg()), then clear the terminal (bext.clear()). When you set the background and foreground colors, you have only a few options to choose from. The allowable list of color choices are black, red, green, yellow, blue, purple, cyan, white, reset, random.

Projet de programme n° 1

D'abord, un petit avertissement sur l'exécution de projets qui utilisent bext dans votre IDE. Puisque bext contrôle les positions et les couleurs dans un terminal, celui utilisé par votre IDE pourrait ne pas fonctionner correctement. S'il s'avère que vous utilisez VS Code, les programmes fonctionneront, mais il faut vous souvenir de cliquer à l'intérieur du terminal en bas de la fenêtre du code. Si vous utilisez Geany, bext fonctionnera aussi, mais la fenêtre du terminal défilera sans doute au-delà de la véritable sortie du programme. Je n'ai pas essayé IDLE, mais je suppose qu'il ne fonctionnera pas. Aussi, créez votre programme dans votre IDE normal, puis ouvrez une fenêtre du terminal pour tester le programme à partir de la ligne de commande. Vous trouverez ci-dessous le code pour notre premier programme bext :

Comme toujours, il faut importer bext. Puisque le programme ne fonctionnera pas sans elle, j'utilise un try | except pour contenir l'argument d'import. Comme cela, s'il échoue, l'utilisateur sait tout de suite pourquoi.

Ensuite, il faut faire un peu de paramétrage. Nous commençons par régler la couleur de l'arrière-plan (background - bext.bg())) et celle du foreground (bext.fg()), puis nous vidons le terminal (bext.clear()). Quand vous réglez les couleurs de l'arrière-plan et de l'avant-plan, il n'y a que quelques options parmi lesquelles choisir. La liste des choix de couleur comporte noir, rouge, vert, jaune, bleu, violet, cyan, blanc, réinitialiser (reset) et aléatoire (random).

Then (next page, top right) we get the width and height of the terminal using bext.size(), since most terminal programs have the ability to change the width and height of the window. Notice that we print the width and height of the terminal screen. Once we do this, we need to print on the next line, not the top line, so we will move the cursor to the far left of the screen, the second line (0,1), print something, then move the cursor to column 10, row 6 and print a test line again. Finally, we move the cursor to the bottom line, position 0 and end the program (code is bottom left). We use the bext.goto() command which takes two parameters, x position (column position) and y position (line of the terminal). Save the program to “bext_demo1.py”. When you run the program in a terminal, it should look something like this…

Ensuite (page suivante, en haut à droite), nous réglerons la largeur et la hauteur du terminal avec bext.size(), puisque la plupart des programmes de terminal ont la capacité de modifier la largeur et la hauteur de la fenêtre.

Remarquez que nous imprimons la largeur et la hauteur de l'écran du terminal. Une fois cela fait, nous devons imprimer sur la ligne suivante, pas sur la ligne du haut ; aussi, nous bougeons le curseur tout à fait à gauche de l'écran, sur la deuxième ligne (0,1), imprimons quelque chose, puis déplaçons le curseur à la colonne 10, rangée 6 et imprimons une autre ligne de test. Pour terminer, nous mettons le curseur sur la dernière ligne, position 0 et terminons le programme (le code se trouve en bas à gauche).

Nous utilisons la commande bext.goto() qui prend deux paramètres, la position x (celle de la colonne) et la position y (la ligne du terminal). Sauvegardez le programme dans « bext_demo1.py ». Quand vous lancez le programme dans un terminal, il doit ressembler à quelque chose comme ceci :

If you happen to be using Gnome Terminal, you can change the size of the terminal by clicking Terminal from the main menu and then the size of the terminal window. I’m sure that most other terminals have the same sort of option. Bext has only a few commands, and you can find a list of them on the bext homepage at https://github.com/asweigart/bext. Now that we have some very basic understanding of the bext library, let’s move on to something a bit more complex. Program Project #2

Si vous utilisez Gnome Terminal, vous pouvez changer la taille du terminal en cliquant sur Terminal dans le menu principal, puis sur la taille de la fenêtre du terminal. Je suis certain que la plupart des autres terminaux ont le même type d'option.

Bext n'a que quelques commandes et vous pouvez en trouver une liste sur la page d'accueil de bext à https://github.com/asweigart/bext.

Maintenant que vous avez une très basique compréhension de la bibliothèque bext, avançons à quelque chose d'un peu plus compliqué.

Projet de programme n° 2

If you actually remember the moon landing (1969), you will remember the terminals that we had to use way back then. If not, there were no cell phones, no personal computers, and no internet. Back in those days, computers were all mainframes, and access was via serial terminals – which were just a keyboard and CRT monitor. The monitors had a black background and (usually) green text. There was no mouse, so the programs had to print out a “form” on the screen, then set the cursor to the proper X,Y position for the input. Once the terminal operator entered the correct (hopefully) information, (s)he used the <ENTER> key to move to the next position on the screen and the whole thing repeated, until all the information was entered. The program we will create emulates a very small version of that. This time, we’ll simply import the bext library import bext Now (below) we’ll create a function to take a string, decide how to center it based on the width of the terminal window, and print it at the proper position.

Si vous pouvez vous souvenir de l'atterissage sur la lune (1969), vous vous souviendrez des terminaux qu'il fallait utiliser en ce temps-là. Sinon, il n'y avait pas de téléphones portables, pas d'ordinateurs personnels et pas d'Internet. À l'époque, les ordinateurs étaient tous des ordinateurs centraux et l'accès s'y faisait via des terminaux série, c'est-à-dire tout simplement un clavier et un moniteur CRT. L'arrière-plan des moniteurs était noir et le texte vert (d'habitude). Il n'y avait pas de souris et les programmes devaient imprimer une « forme » sur l'écran puis régler le curseur à la bonne postion X,Y pour l'entrée. Une fois que l'opérateur du terminal avait entré les informations correctes (avec un peu de chance), il ou elle utilisait la touche <ENTRÉE> pour se déplacer à la position suivante sur l'écran et le tout se répétait jusqu'à ce que toutes les informations soient entrées. Le programme que nous allons créer émule une toute petite version de cela.

Cette fois-ci, nous allons importer la bibliothèque bext de façon simple.

import bext

Maintenant (ci-dessous), nous créerons une fonction qui prendra une chaîne, décidera comment la centrer compte tenu de la largeur de la fenêtre du terminal et l'imprimera à la bonne position.

Now (next page, top right) we’ll create some lists to hold the X,Y positions for each prompt in the form, hold the text that will be printed for each, and the X,Y positions for the placement of the cursor to receive the inputs. Now (below) we’ll create a function to handle the input of each data item. We’ll simply use the input() function for this… Notice that before we call the GetEntry() function to get the data, we call SetUpScreen() function again, but this time, we pass a True, to invert the colours for each input field.

Maintenant (en haut et à droite de la page suivante), nous créons quelques listes qui contiendront les positions X,Y pour chaque invite dans la forme, le texte qui sera imprimé pour chacune, et les positions X,Y du curseur pour qu'il reçoive les entrées.

Maintenant (ci-dessous), nous créons une fonction pour gérer l'entrée de chaque donnée. Nous utiliserons tout simplement la fonction input() pour ce faire :

Remarquez que, avant d'appeler la fonction GetEntry() pour obtenir les données, nous appelons la fonction SetUpScreen() à nouveau, mais cette fois-ci, nous passons un True (Vrai) pour inverser les couleurs pour chaque champ d'entrée.

Save your program as “Bext_test1.py”, and run it in a terminal. It should look something like this… That’s it. You can find the code for the two projects at my github repository https://github.com/gregwa1953/FCM-169. Just as an aside, the bext library was written by Al Sweigart. I have done a book review on his latest book in this issue of Full Circle. Next month, we’ll take a look at extracting text from a PDF file. Until next time, as always; stay safe, healthy, positive and creative!

Sauvegardez votre programme comme « Bext_test1.py » et lancez-le dans un terminal. Il devrait ressembler à ceci :

Et voilà. Vous trouverez le code pour les deux projets dans mon dépôt github https://github.com/gregwa1953/FCM-169.

Soit dit en passant, c'est Al Sweigart qui a écrit la bibliothèque bext. J'ai fait une critique de son nouveau livre dans ce numéro du FCM.

Le mois prochain, nous regarderons comment extraire du texte d'un fichier PDF.

Jusqu'à la prochaine fois, comme toujours, restez prudent, en bonne santé, positif et créatif !

Page 34, encart en bas à droite, lignes noires au milieu : Next, we’ll create a function that will set the colors for foreground and background, and take a parameter to invert those colors ( swap the foreground and background colors)

Ensuite nous créerons une fonction qui règlera les couleurs d'avant et d'arrière-plan et prendrons un paramètre pour inverser ces couleurs (échange des couleurs entre l'avant et l'arrière-plan).

Page 35, encart en haut à droite, lignes noires au milieu : At this point, we’ll create a function to fill the screen with our prompts.

Ici, nous créerons une fonction qui remplit l'écran avec nos invites.

Page 35, encart en bas à gauche, lignes noires au milieu : Finally, we call our functions. Notice that we call SetUpScreen() with False as the parameter to set the text colors to a black background and green foreground.

Enfin nous appelons nos fonctions. Notez que nous appelons SetUpScreen() avec Falsecomme paramètre pour régler les couleurs du texte avec arrière-plan noir et texte vert.

issue169/python.txt · Dernière modification : 2021/06/05 16:10 de andre_domenech