Outils pour utilisateurs

Outils du site


issue176: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
issue176:python [2022/01/03 08:45] d52frissue176:python [2022/01/06 15:28] (Version actuelle) andre_domenech
Ligne 2: Ligne 2:
  
 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?).** 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 **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
Ligne 16: Ligne 21:
 greg@earth:~$ pip3 --version greg@earth:~$ pip3 --version
 pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)** 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. **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.
Ligne 26: Ligne 46:
  
 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.** 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… **With the terminal still open, try the following command…
Ligne 40: Ligne 71:
  
 sw, sh = pyautogui.size()** 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. **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.
Ligne 48: Ligne 94:
  
 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.** 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. **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.
Ligne 62: Ligne 117:
  
 pyautogui.alert(text='Finished!', title='PYAUTOGUI TEST', button='OK')** 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. **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.
Ligne 72: Ligne 142:
  
 Now, while this isn’t the most useful example of the capabilities of pyautogui, our next project should give you a really good one.** 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… **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…
Ligne 78: Ligne 159:
  
 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.** 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. **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.
Ligne 93: Ligne 181:
  
 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.** 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. **After the sleep time has elapsed, you should see the word “password” appear, followed by another sleep time.
Ligne 109: Ligne 212:
  
 Until next time, as always; stay safe, healthy, positive and creative!** 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.1641195937.txt.gz · Dernière modification : 2022/01/03 08:45 de d52fr