Outils pour utilisateurs

Outils du site


issue170:python

As many of you know, I work fairly closely with Don Rozenberg who is the author of PAGE. For over 10 years, he and I have communicated strictly via email. Until the last 30 days or so. Now we are enjoying Discord video chat (voice only (my choice)) and screen sharing. It makes our communications and collaboration tremendously productive. The immediate back-and-forth is awesome, and we get a tonne of things done, talked through, and most importantly, because it’s live, understanding is immediate. I can’t tell you how many email threads that we’ve gone through where one or the other of us doesn’t quite understand an issue without 5 or more emails back-and-forth. Given the time-zone issue, there are many times that it takes 3 or 4 days to hash out a problem or thought. Now he can see what I’m doing and I can see what he is doing. If you haven’t tried Discord and the screen share/voice session before, you owe it to yourself to find someone to try it with. It’s not the most intuitive thing in the world, but with a bit of patience, it’s easy to get up to speed quickly. Now the reason I am mentioning this is because, on today’s update session, he asked if I had ever used PtPython. I honestly said no, and he proceeded to demo it for me and I was immediately impressed. (Note that I’m fairly easy to impress, so that’s not a big thing.) While he was showing me what it can do, I grabbed my smartphone and looked it up. I decided right then and there to use it as my article for this month.

Comme beaucoup d'entre vous le savent, je travaille en étroite collaboration avec Don Rozenberg, l'auteur de PAGE. Pendant plus de 10 ans, nous avons communiqué strictement par courriel. Jusqu'à ces 30 derniers jours environ. Maintenant, nous profitons du chat vidéo Discord (voix seulement (mon choix)) et du partage d'écran. Cela rend nos communications et notre collaboration extrêmement productives. Le dialogue immédiat est génial, et nous parvenons à faire une tonne de choses et à en discuter, et surtout, comme c'est en direct, la compréhension est immédiate. Je ne peux pas vous dire combien de fils de mails nous avons écrits où l'un ou l'autre d'entre nous ne comprenait pas bien un problème sans qu'il y ait 5 allers-et-retours de mails ou plus. Étant donné le problème des fuseaux horaires, il arrive souvent qu'il faille 3 ou 4 jours pour régler un problème ou une idée. Maintenant, il peut voir ce que je fais et je peux voir ce qu'il fait. Si vous n'avez jamais essayé Discord et le partage d'écran/la session vocale, vous vous devez de trouver quelqu'un avec qui l'essayer. Ce n'est pas la chose la plus intuitive du monde, mais avec un peu de patience, il est facile de se mettre rapidement à niveau.

La raison pour laquelle je mentionne ceci est que, lors de la session de mise à jour d'aujourd'hui, il m'a demandé si j'avais déjà utilisé PtPython. J'ai répondu honnêtement que non, et il a procédé à une démonstration pour moi et j'ai été immédiatement impressionné. (Notez que je m'impressionne facilement et que ce n'est donc pas grand' chose.) Pendant qu'il me montrait ce que le logiciel peut faire, j'ai pris mon smartphone et j'ai fait des recherches. J'ai décidé à ce moment-là de l'utiliser pour mon article de ce mois-ci.

You can find the home page for PtPython at https://github.com/prompt-toolkit/ptpython. I have to admit that I REALLY hate the “normal” Python Interactive Shell or REPL. While it’s very useful many times to test code before I try to make it work in my IDE, I find it very clumsy especially when I’m trying to prototype a function or complex loop. More times than not, I’ll just work it up in VS Code and if it doesn’t work, I’ll set a breakpoint and step through my code until I find where I have messed up. One of the reasons that I was so excited about PtPython is that it allows you to use history to dump an entire loop or function back into active code and make a quick edit due to a typo. Let’s take a look at using PtPython. First, we need to install it. You can use pip to do this… pip install ptpython However, when I did this, I received a number of dependency errors. So, I uninstalled it, downloaded the repository as a zip file, unpacked it and then did an “old-fashioned” python install from the repository folder… python setup.py install Then I installed it again via pip and everything seemed to work. The first thing you might notice is that, unlike the “normal” Python REPL, it doesn’t start with the version number. That, you can find in the bottom right of the window.

Vous trouverez la page d'accueil de PtPython à l'adresse https://github.com/prompt-toolkit/ptpython.

Je dois admettre que je déteste VRAIMENT le shell interactif Python ou REPL « normal ». Bien qu'il soit souvent très utile pour tester du code avant d'essayer de le faire fonctionner dans mon IDE, je le trouve très maladroit, surtout lorsque j'essaie de prototyper une fonction ou une boucle complexe. La plupart du temps, je me contente de travailler dans VS Code et si cela ne fonctionne pas, je place un point d'arrêt et je parcours mon code jusqu'à ce que je trouve l'endroit où je me suis trompé.

L'une des raisons pour lesquelles j'étais si enthousiaste à propos de PtPython, c'est qu'il vous permet d'utiliser l'historique pour replacer une boucle ou une fonction entière dans le code actif et faire une modification rapide en cas de faute de frappe.

Voyons comment utiliser PtPython. Tout d'abord, nous devons l'installer. Vous pouvez utiliser pip pour le faire :

pip install ptpython

Cependant, lorsque j'ai fait cela, j'ai reçu un certain nombre d'erreurs de dépendance. Donc, je l'ai désinstallé, j'ai téléchargé le dépôt sous forme de fichier zip, je l'ai décompressé et j'ai fait une installation python « à l'ancienne » à partir du dossier du dépôt :

python setup.py install

Puis je l'ai installé à nouveau via pip et tout semblait fonctionner.

La première chose que vous pouvez remarquer, c'est que, contrairement au REPL Python « normal », il ne commence pas par le numéro de version. Celui-ci se trouve en bas à droite de la fenêtre.

Now this is where I started to kind of “choke up”. I couldn’t for the life of me, come up with anything to try. So, I did a simple test purposefully making a mistake… »> a = 3 »> b = 2 »> for cntr in range(a): … for cntr2 in range(b): … print(f'{a} - {b}') 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2 »> Instead of printing the values of cntr and cntr2, I told it to print a and b. To fix the error, I simply pressed the up arrow key. It then put in my entire loop. I then used the left arrow and replaced the “a” with “cntr” and the “b” with “cntr2”. I then pressed {enter} twice and the output is as I wanted it. Much better. AND MUCH easier than dealing with the standard REPL. As I got ready to do the next section below, I remembered that there is autocomplete already built into ptpython. For example… Just one more checkmark for ptpython! Now that I’d gotten all that done, I started thinking to myself, “Self, what else can I do to show the goodies that ptpython has to offer?” And I answered myself, “Well, Self, how about showing off the PyWebIO library at the same time you show off the ptpython?”. Who am I to argue with myself, right? So, here we go.

C'est là que j'ai commencé à m'étouffer. Je n'arrivais pas du tout à trouver quelque chose à essayer. Donc, j'ai fait un test simple en faisant exprès de faire une erreur :

a = 3
b = 2
for cntr in range(a) :

… for cntr2 in range(b) : … print(f'{a} - {b}') 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2 3 - 2

Au lieu d'imprimer les valeurs de cntr et cntr2, je lui ai dit d'imprimer a et b. Pour corriger l'erreur, j'ai simplement appuyé sur la touche de déplacement vers le haut. Le programme a alors inséré ma boucle complète. J'ai ensuite utilisé la flèche gauche et remplacé le « a » par « cntr » et le « b » par « cntr2 ».

J'ai ensuite appuyé deux fois sur {enter} et le résultat est tel que je le voulais. C'est beaucoup mieux. ET BEAUCOUP plus facile que de le faire avec le REPL standard.

Alors que je me préparais à faire la prochaine section ci-dessous, je me suis souvenu qu'il y a une autocomplétion déjà intégrée dans ptpython. Par exemple : Et une coche de plus en faveur de ptpython !

Maintenant que j'ai fait tout ça, j'ai commencé à me dire : « Dis, qu'est-ce que tu peux faire d'autre pour montrer les petits plus que ptpython offre ? » Et je me suis répondu : « Eh bien, que dirais-tu de montrer la bibliothèque PyWebIO tout en présentant ptpython ? » Qui suis-je pour me contredire, n'est-ce pas ? Donc, nous y voilà.

PyWebIO According to their website https://github.com/wang0618/PyWebIO, “PyWebIO provides a series of imperative functions to obtain user input and output on the browser, turning the browser into a “rich text terminal”, and can be used to build simple web applications or browser-based GUI applications without the need to have knowledge of HTML and JS.” I stumbled across this library while trying to keep up with the news about Python while trying to deal with other things. I wasn’t really sure when I was going to be able to show it to you, but as they used to say, “There’s no present like the time”. Well, THEY say it differently, but I like to be different. So, to install it, simply use pip… pip3 install pywebio And you are ready to go. Now in ptpython, do an import of the package… »> from pywebio.output import *

PyWebIO

Selon leur site web https://github.com/wang0618/PyWebIO

« PyWebIO fournit une série de fonctions impératives pour obtenir l'entrée et la sortie de l'utilisateur sur le navigateur, transformant le navigateur en un « terminal de texte riche », qui peut être utilisé pour construire des applications Web simples ou des applications avec interface graphique basées sur le navigateur sans devoir avoir des connaissances en HTML et JS. »

Je suis tombé sur cette bibliothèque en essayant de suivre l'actualité de Python tout en m'occupant d'autres choses. Je n'étais pas vraiment sûr du moment où j'allais pouvoir vous la montrer, mais comme on disait autrefois « Il n'y a pas de présent comme l'heure ». Eh bien, ILS le disent différemment, mais j'aime être différent.

Donc, pour l'installer, il suffit d'utiliser pip :

pip3 install pywebio

Et vous êtes prêt à y aller.

Maintenant dans ptpython, faites un import du paquet :

from pywebio.output import *

Now, I’m going to try to recreate the terminal animation that they have on their website. »> put_text(“Hello World!”); When you do this, your default web browser should pop open and show you… Easy enough, right? Now, let’s do something a bit fancier… »> put_table([ … ['Product', 'Price'], … ['Apple', '$5.5'], … ['Banner', '$7'], … ]); »> And your browser window will update to show… Those are some expensive apples, but it gets the point across. Tables are REALLY easy. Notice that it automatically made the headers bold. We can even, easily, put a logo onto the web page… »> put_image(open('FullCircleLogo.jpg','rb').read());

Maintenant, je vais essayer de recréer l'animation du terminal qu'ils ont sur leur site Web.

put_text(“Hello World !”) ;

Lorsque vous faites cela, votre navigateur Web par défaut devrait s'ouvrir et vous montrer :

C'est assez simple, non ? Maintenant, faisons quelque chose d'un peu plus sophistiqué :

put_table([

… ['Product', 'Prix'], … ['Apple', '$5.5'], … ['Banner', '$7'], … ]) ;

Et la fenêtre de votre navigateur sera mise à jour pour afficher :

Ces pommes-là sont vachement chères, mais elles permettent de faire passer le message. Les tableaux sont VRAIMENT faciles. Remarquez qu'il a automatiquement mis les en-têtes en gras.

Nous pouvons même, facilement, mettre un logo sur la page Web :

put_image(open('FullCircleLogo.jpg', 'rb').read()) ;

You can even put interactive buttons on your web page… »> def on_click(btn): … put_markdown(“You clicked '%s' button” % btn) »> »> put_buttons(['A', 'B','C'], onclick=on_click); »> Which shows three buttons, just like we asked. When you click each, this is what it will look like… There is so much more that can be done with these two packages, that really, your imagination is your only limitation. This month’s article will really stress Ronnie getting everything to line up, so I think it might be a good idea that I end up. (I'd rather line up images than try and line up all those usual code snippets! - Ronnie) Until next time, as always; stay safe, healthy, positive and creative!

Vous pouvez même mettre des boutons interactifs sur votre page Web :

def on_click(btn) :

… put_markdown(“Vous avez cliqué sur le '%s' bouton” % btn)

put_buttons(['A', 'B', 'C'], onclick=on_click) ;

Ce qui montre trois boutons, comme nous l'avons demandé. Lorsque vous cliquez sur chacun d'eux, voici ce à quoi ça ressemblera :

Il y a tellement plus de choses qui peuvent être faites avec ces deux paquets, que votre seule limite est votre imagination.

L'article de ce mois-ci va vraiment stresser Ronnie pour que tout soit aligné, donc je pense que c'est une bonne idée que je m'arrête. (Je préfère aligner des images plutôt que d'essayer d'aligner tous ces bouts de code habituels ! - Ronnie.)

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

issue170/python.txt · Dernière modification : 2021/06/29 18:04 de auntiee