Outils pour utilisateurs

Outils du site


issue176:python

It’s unusual for me to get questions more than once a month. However, today, while I was thinking about what I was going to do for my Python article for December, I got a question from a friend about my suggestions for doing automated testing of his program. Immediately, I suggested pyautogui. I passed a copy of my article from FCM#151, which came out in November 2019. A few hours later, another friend and client contacted me and asked what would be a good library for mouse and keyboard emulation. Once again, I immediately suggested pyautogui and sent him a copy of the article as well. Once things quieted down a bit around the old homestead, I realized that the Cosmic Muffin was trying to tell me something. So I started looking at the latest documentation for pyautogui and found that Al Sweigart has really updated things quite a bit. You can find that documentation at https://pyautogui.readthedocs.io/en/latest/index.html. You might want to get some more background by looking at his online version of Automating The Boring Stuff with Python at https://automatetheboringstuff.com/ and jumping to chapter 20. I STRONGLY suggest that you purchase this book for your library and support Al for all his wonderful work over the years. (Can you tell he’s one of my favorite authors?).

Il est inhabituel pour moi de recevoir des questions plus d'une fois par mois. Cependant, aujourd'hui, alors que je réfléchissais à ce que j'allais faire pour mon article sur Python du mois de décembre, j'ai reçu la question d'un ami qui voulait savoir ce que je pouvais lui suggérer pour faire des tests automatisés de son programme. Immédiatement, j'ai suggéré pyautogui. Je lui ai donné une copie de mon article du FCM n°151, qui est sorti en novembre 2019. Quelques heures plus tard, un autre ami et client m'a contacté et m'a demandé quelle serait une bonne bibliothèque pour l'émulation de la souris et du clavier. Une fois de plus, j'ai immédiatement suggéré pyautogui et lui ai également envoyé une copie de l'article.

Une fois que les choses se sont calmées un peu autour de la maison, j'ai réalisé que le Cosmic Muffin essayait de me dire quelque chose. J'ai donc commencé à consulter la dernière documentation de pyautogui et j'ai découvert qu'Al Sweigart avait vraiment mis les choses à jour. Vous pouvez trouver cette documentation à l'adresse https://pyautogui.readthedocs.io/en/latest/index.html. Pour en savoir plus, vous pouvez consulter sa version en ligne de Automating The Boring Stuff with Python (Automatiser les trucs ennuyeux avec Python) à l'adresse https://automatetheboringstuff.com/ et sauter au chapitre 20. Je vous conseille vivement d'acheter ce livre pour votre bibliothèque et de soutenir Al pour tout le travail formidable qu'il a accompli au fil des ans. (Avez-vous compris qu'il est l'un de mes auteurs préférés ?)

The first thing to do is to install or update pyautogui. Some of my friends and readers seem to have more than one version of Python (and pip) installed. So let’s use some simple commands from the terminal to determine the proper commands for your system. Open a terminal and type python -V and pip –version greg@earth:~$ python -V Python 3.8.10 greg@earth:~$ pip –version pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8) This will give you the current versions of Python version and pip, which should be the same. You might also want to try python3 -V and pip3 –version to verify that the versions are the same. greg@earth:~$ python3 -V Python 3.8.10 greg@earth:~$ pip3 –version pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)

La première chose à faire est d'installer ou de mettre à jour pyautogui. Certains de mes amis et lecteurs semblent avoir plus d'une version de Python (et pip) installée. Utilisons donc quelques commandes simples à partir du terminal pour déterminer les commandes appropriées pour votre système. Ouvrez un terminal et tapez python -V et pip –version

greg@earth:~$ python -V Python 3.8.10 greg@earth:~$ pip –version pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)

Cela vous donnera les versions actuelles de Python et de pip, qui devraient être les mêmes. Vous pouvez également essayer python3 -V et pip3 –version pour vérifier que les versions sont les mêmes.

greg@earth:~$ python3 -V Python 3.8.10 greg@earth:~$ pip3 –version pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)

If the versions of python and pip are not the same, pick one of the versions and use the proper python and pip combination that you wish to install pyautogui into. Since mine are the same, I just used the pip command. Next page, on the right, is an abbreviated version of the terminal output from my system when I installed pyautogui on my system (your terminal output will probably be a bit different)… Now that pyautogui is installed, you might have to install one more thing. If you try to run pyautogui right now, you might not have a package and will get an error. You need to be sure that the package scrot is installed on your Linux system. You can do this by using the still open terminal to verify it. $ sudo apt install scrot Scrot stands for SCReenshOT. If you are running a Windows system, you might have to use a different screenshot package. Pyautogui will tell you what else is needed. Assuming everything is installed correctly, we can move forward.

Si les versions de python et pip ne sont pas les mêmes, choisissez l'une des versions et utilisez la bonne combinaison python et pip dans laquelle vous souhaitez installer pyautogui. Comme les miennes sont les mêmes, j'ai juste utilisé la commande pip.

Sur la page suivante, à droite, se trouve une version abrégée de la sortie du terminal de mon système lorsque j'y ai installé pyautogui (la sortie de votre terminal sera probablement un peu différente).

Maintenant que pyautogui est installé, vous devrez peut-être installer encore une chose. Si vous essayez d'exécuter pyautogui maintenant, il se peut qu'il vous manque un paquet et que vous obteniez une erreur. Vous devez être sûr que le paquet scrot est installé sur votre système Linux. Vous pouvez le faire en utilisant le terminal encore ouvert pour le vérifier.

$ sudo apt install scrot

Scrot est l'abréviation de SCReenshOT. Si vous utilisez un système Windows, vous devrez peut-être utiliser un paquet de capture d'écran différent. Pyautogui vous dira ce qui est nécessaire. En supposant que tout est installé correctement, nous pouvons continuer.

With the terminal still open, try the following command… $ python -m mouseinfo If everything is working, you should see a window open that looks something like this… This is a new utility that comes with pyautogui that makes automation of the mouse and keyboard really simple. It will show you the X and Y positions on the screen where you need to direct the mouse pointer to allow for text or mouse clicks. Notice the four buttons on the right (upper) of the window. The Log All (F5) and Log XY (F6) will allow you to save the mouse positions to a file, along with the Save Log button on the lower right of the window. Now, let’s write a simple program to move the mouse around the screen just to verify everything is working. Save the program as “test1.py”, but before you run the program, let’s look at a few of the lines. The first line we will examine is… sw, sh = pyautogui.size()

Le terminal étant toujours ouvert, essayez la commande suivante :

$ python -m mouseinfo

Si tout fonctionne, vous devriez voir une fenêtre ouverte qui ressemble à quelque chose comme ceci :

Il s'agit d'un nouvel utilitaire fourni avec pyautogui qui rend l'automatisation de la souris et du clavier vraiment simple. Il vous montrera les positions X et Y sur l'écran où vous devez diriger le pointeur de la souris pour permettre la saisie de texte ou les clics de souris. Remarquez les quatre boutons sur la droite (en haut) de la fenêtre. Les boutons Log All (F5) et Log XY (F6) vous permettront d'enregistrer les positions de la souris dans un fichier, ainsi que le bouton Save Log en bas à droite de la fenêtre.

Maintenant, écrivons un programme simple pour déplacer la souris sur l'écran, juste pour vérifier que tout fonctionne.

Enregistrez le programme sous le nom de « test1.py », mais avant d'exécuter le programme, examinons quelques lignes. La première ligne que nous allons examiner est :

sw, sh = pyautogui.size()

This will return the width and height of your screen in pixels. I have two monitors hooked to my system, so Linux combines the width of both and reports that as the width. It takes the height of the primary monitor. Be sure to take these values into consideration when you use the moveTo functions. Speaking of the moveTo function, the next line we need to look at is the first moveTo line. pyautogui.moveTo(10, 10, duration=0.50) The parameters are (Xposition, Yposition, Duration). Be sure you use proper values for your system. Remember that Xposition is the horizontal or right/left position on the screen and the Yposition is the vertical or top/bottom position on your screen. The Duration setting is how many milliseconds the movement will take. It’s completely optional, but by setting the value at 0.50, we can actually watch the mouse cursor move on the screen. In your future use, you might want to not include the duration parameter, to speed things up.

Celle-ci renvoie la largeur et la hauteur de votre écran en pixels. J'ai deux moniteurs connectés à mon système, donc Linux combine la largeur des deux et la rapporte comme largeur. Il prend la hauteur du moniteur principal. Veillez à prendre ces valeurs en considération lorsque vous utilisez des fonctions moveTo.

À propos de la fonction moveTo, la prochaine ligne que nous devons examiner est la première ligne moveTo :

pyautogui.moveTo(10, 10, duration=0.50)

Les paramètres sont (Xposition, Yposition, Duration). Assurez-vous d'utiliser les valeurs appropriées pour votre système. Rappelez-vous que Xposition est la position horizontale ou droite/gauche sur l'écran et que Yposition est la position verticale ou haut/bas sur votre écran. Le paramètre Duration indique le nombre de millisecondes que prendra le mouvement. C'est complètement facultatif, mais en fixant la valeur à 0,50, nous pouvons réellement regarder le curseur de la souris se déplacer sur l'écran. À l'avenir, vous pourriez ne pas inclure le paramètre de durée, pour accélérer les choses.

We will move to near the upper left of the monitor, then the upper right of the monitor, then to near the lower right of the monitor then to somewhere around the center of the monitor. Next, the mouse will move to position 139, 250 and perform a mouse click in the text editor to make sure it’s selected as the target for the text we will eventually send. pyautogui.click(139, 250) You will want to open a text editor and make sure the entry area of the editor will be available for this, since we are about to enter some text into the text editor, using the write function. pyautogui.write('Hello from Python!!!') As you might guess, being the observant reader that you are, the write function emulates “standard” keyboard keypresses, and writes whatever is set as the parameter to the function to the current mouse position. The final thing that gets done in our test program is that we show a message box from pyautogui saying the program has finished and will then wait for you to manually click the OK button. pyautogui.alert(text='Finished!', title='PYAUTOGUI TEST', button='OK')

Nous nous déplacerons vers la partie supérieure gauche du moniteur, puis vers la partie supérieure droite du moniteur, puis vers la partie inférieure droite du moniteur et enfin vers le centre du moniteur.

Ensuite, la souris se déplacera à la position 139, 250 et effectuera un clic de souris dans l'éditeur de texte pour s'assurer qu'il est sélectionné comme cible pour le texte que nous enverrons ultérieurement :

pyautogui.click(139, 250)

Ouvrez un éditeur de texte et vous assurer que la zone de saisie de l'éditeur sera disponible pour cela, puisque nous sommes sur le point de saisir du texte dans l'éditeur de texte, en utilisant la fonction write :

pyautogui.write('Bonjour de Python !!!')

Comme vous pouvez le deviner, en tant que lecteur observateur, la fonction write émule les pressions de touches « standard » du clavier, et écrit ce qui est défini comme paramètre de la fonction à la position actuelle de la souris. La dernière chose qui est faite dans notre programme de test est l'affichage d'une boîte de message de pyautogui indiquant que le programme est terminé et qu'il attend que vous cliquiez manuellement sur le bouton OK :

pyautogui.alert(text='Finished!', title='PYAUTOGUI TEST', button='OK')

Hopefully, you have the mouseinfo program still running. You can move the mouse to the positions that are coded in the demo program, just to make sure that they fit for your system. If not, all you have to do is modify the positions in the moveTo or click functions to make sure everything works. Now, making sure that the text editor is open and in the proper place, you can simply open another terminal in the folder where you saved your python test1.py program, and run it. $python test1.py If everything worked correctly, you can watch the mouse pointer move around the screen, eventually moving into the text editor and sending the message. Now, while this isn’t the most useful example of the capabilities of pyautogui, our next project should give you a really good one.

Avec un peu de chance, le programme mouseinfo est toujours en cours d'exécution. Vous pouvez déplacer la souris vers les positions qui sont codées dans le programme de démonstration, juste pour vous assurer qu'elles conviennent à votre système. Si ce n'est pas le cas, il vous suffit de modifier les positions dans les fonctions moveTo ou click pour vous assurer que tout fonctionne.

Maintenant, en vous assurant que l'éditeur de texte est ouvert et au bon endroit, vous pouvez ouvrir un autre terminal dans le dossier où vous avez enregistré votre programme python test1.py, et l'exécuter :

$python test1.py

Si tout a fonctionné correctement, vous pouvez voir le pointeur de la souris se déplacer sur l'écran, pour finalement se placer dans l'éditeur de texte et envoyer le message.

Si cet exemple n'est pas le plus utile pour montrer les capacités de pyautogui, notre prochain projet devrait vous en donner un bien meilleur.

I’ve been working on a new tutorial for the next version of PAGE for Don Rozenberg. The first project in the tutorial is to create a login form which has an entry box for Username and Password, and a button to “submit” the information. I won’t go into the code very much and the actual project can be found on the repository (mentioned at the end of this article). The program looks something like this… The reason I chose this was that I know exactly where the form will appear on the screen, every time it runs, so it will make an easy demo for you to follow. You can use the MouseInfo program to verify the positions of the Entry widgets on your system and the button by running the login.py program, then watching the XY Position as you hover over the widgets. If they are off a great deal, you can modify it in our test2 program, which is presented next page, top right.

Je travaille pour Don Rozenberg sur un nouveau tutoriel pour la prochaine version de PAGE. Le premier projet du tutoriel est de créer un formulaire de connexion qui a une boîte de saisie pour le nom d'utilisateur et le mot de passe, et un bouton pour « soumettre » l'information. Je n'entrerai pas beaucoup dans le code et le projet réel peut être trouvé sur le dépôt (mentionné à la fin de cet article). Le programme ressemble à quelque chose comme ceci :

La raison pour laquelle j'ai choisi ce programme est que je sais exactement où le formulaire apparaîtra à l'écran, à chaque fois qu'il s'exécute, ce qui en fait une démo facile à suivre pour vous.

Vous pouvez utiliser le programme MouseInfo pour vérifier les positions des widgets Entry sur votre système et du bouton en exécutant le programme login.py, puis en observant la position XY lorsque vous survolez les widgets. S'ils sont très décalés, vous pouvez les modifier dans notre programme test2, qui est présenté à la page suivante, en haut à droite.

You can see that everything in the code of the test program has already been talked about from our test1 program. I set the time.sleep() call to 10 seconds, so I could take screenshots for the article. You can set it to a value that works for you. Now you will hopefully have downloaded all the code from the repository and unpacked it into a convenient folder then open two terminals within that folder. The first terminal is to run the login.py program and the second is to run the test2.py program. So, open your first terminal and type… $python login.py In the second terminal, making sure that nothing is obstructing the login form, you want to type… $python test2.py The first thing you should see is the cursor jump to the first Entry widget of the login form and the username Greg should appear.

Vous pouvez voir que tout dans le code du programme de test a déjà été abordé dans notre programme test1. J'ai fixé l'appel à time.sleep() à 10 secondes, afin de pouvoir faire des captures d'écran pour l'article. Vous pouvez le fixer à une valeur qui vous convient.

Maintenant, vous aurez, je l'espère, téléchargé tout le code du dépôt et l'aurez décompressé dans un dossier pratique ; ensuite, ouvrez deux terminaux dans ce dossier. Le premier terminal est destiné à exécuter le programme login.py et le second est destiné à exécuter le programme test2.py.

Bon. Ouvrez votre premier terminal et tapez :

$python login.py

Dans le second terminal, en vous assurant que rien n'obstrue le formulaire de connexion, vous devez taper :

$python test2.py

La première chose que vous devriez voir est le curseur qui saute au premier widget d'entrée du formulaire de connexion, et le nom d'utilisateur Greg devrait apparaître.

After the sleep time has elapsed, you should see the word “password” appear, followed by another sleep time. Finally, another sleep period should expire and the Continue button should get “pressed”, resulting in a message box from the program. Immediately after that, the message box from pyautogui should pop-up as well. Click the OK buttons on both of the message boxes, and the programs should end. There is a lot more that pyautogui can do, we’ve just scratched the surface. Please take some time to read through the documentation, and Al’s chapter 20, to take advantage of this tremendous resource. The repository for the code is at https://github.com/gregwa1953/FCM-176 I hope that you found this revisitation of pyautogui helpful, and that it encourages you to try automated testing for your future projects. Until next time, as always; stay safe, healthy, positive and creative!

Une fois le temps d'attente écoulé, vous devriez voir apparaître le mot « password », suivi d'un autre temps d'attente.

Enfin, une autre période de sommeil devrait expirer et le bouton Continuer devrait être « enfoncé », ce qui fait apparaître une boîte de message du programme.

Immédiatement après, la boîte de message de pyautogui devrait également apparaître.

Cliquez sur les boutons OK des deux boîtes de message, et les programmes devraient se terminer.

Pyautogui peut faire beaucoup plus ; nous n'avons fait qu'en effleurer la surface. Prenez le temps de lire la documentation, et le chapitre 20 d'Al, pour profiter de cette formidable ressource.

Le dépôt pour le code est à https://github.com/gregwa1953/FCM-176.

J'espère que vous avez trouvé utile cette revisite de pyautogui, et qu'elle vous encourage à essayer les tests automatisés pour vos futurs projets.

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

issue176/python.txt · Dernière modification : 2022/01/06 15:28 de andre_domenech