Outils pour utilisateurs

Outils du site


issue184:tutoriel1

Greg's regular Python series will be back next month. If you are anything like me, after a few years of exposure, the ability to write Bash scripts seemed to get automatically absorbed in my psyche by osmosis. I have also tinkered with Python but find Bash comes so easily to me that I've struggled to justify committing lots of time to learning it to the same level. Even though admittedly, there have been times when Lambda functions or Python dictionaries would have probably meant less effort overall, I still persevered with Bash. Recently, I was pleasantly surprised to discover someone skilled had created a Bash script/Python script converter called “bash2py” (https://www.swag.uwaterloo.ca/bash2py/index.html). And, following that piece of wizardry, another clever person wrapped bash2py up into a Docker image for ease of use (https://zwischenzugs.com/2016/08/29/bash-to-python-converter). Keen to see if it worked, I thought I would try bash2py with a simple script – as we'll see in a moment. At this stage, it's definitely worth pointing out that you will get mixed results with tools like this one. The author of bash2py states that it is intended to only “do the lion share of the translation effort”. And, additionally, if your Bash script contains errors, surprisingly so will the resulting Python script! You have been warned.

La série régulière de Greg sur Python sera de retour le mois prochain.

Si vous êtes un peu comme moi, après quelques années d'exposition, la capacité à écrire des scripts Bash semble avoir été automatiquement absorbée par osmose dans ma psyché. J'ai également bricolé avec Python, mais je trouve que Bash me vient si facilement que j'ai du mal à justifier la consécration de beaucoup de temps pour atteindre le même niveau d'apprentissage. Même s'il est vrai qu'il y a eu des moments où les fonctions Lambda ou les dictionnaires Python auraient probablement représenté moins d'efforts dans l'ensemble, j'ai quand même persévéré avec Bash.

Récemment, j'ai été agréablement surpris de découvrir que quelqu'un de compétent avait créé un convertisseur de script Bash/Python appelé « bash2py » (https://www.swag.uwaterloo.ca/bash2py/index.html).

Et, à la suite de ce tour de passe-passe, une autre personne intelligente a intégré bash2py dans une image Docker pour en faciliter l'utilisation (https://zwischenzugs.com/2016/08/29/bash-to-python-converter).

Désireux de voir si cela fonctionnait, j'ai pensé essayer bash2py avec un simple script - comme nous le verrons dans un instant. À ce stade, il est important de souligner que vous obtiendrez des résultats mitigés avec des outils comme celui-ci. L'auteur de bash2py déclare qu'il est destiné à ne faire que « la part du lion de l'effort de traduction ». De plus, si votre script Bash contient des erreurs, il est surprenant de constater que le script Python résultant en contiendra aussi ! Vous êtes prévenus.

That said, for relatively simple jobs, like a Lambda function in AWS for example, this tool should be able to give you the building blocks in Python that could be further developed upon. Simple Bash Script Here's a simple script I wrote in order to test out the converter. Its purpose is to employ the very latest technological advances, and… as quickly as possible, it counts to five. The Bash script is shown above. I have saved the Bash script as a file called “bash.sh”. We’ll save it again in a moment, so stay tuned. To test it works, I ran these commands: chmod +x bash.sh ./bash.sh I am a Bash script and I can count… 1 2 3 4 5 I can see the script, counting to five, so we’re all set.

Cela dit, pour des tâches relativement simples, comme une fonction Lambda dans AWS par exemple, cet outil devrait être en mesure de vous fournir des blocs de construction en Python qui pourraient être développés plus avant.

Simple script Bash

Voici un script simple que j'ai écrit afin de tester le convertisseur. Son but est d'utiliser les toutes dernières avancées technologiques, et… le plus rapidement possible, il compte jusqu'à cinq. Le script Bash est présenté ci-dessus.

J'ai enregistré le script Bash dans un fichier appelé « bash.sh ». Nous allons le sauvegarder à nouveau dans un moment, alors restez à l'écoute. Pour tester son fonctionnement, j'ai exécuté ces commandes :

chmod +x bash.sh

./bash.sh

Je suis un script Bash et je peux compter…

1 2 3 4 5

Je peux voir le script comptant jusqu'à cinq et nous sommes donc prêts.

Resulting Python Script Now that we have a simple Bash script, let's see what bash2py makes of it. We will use the Docker image approach. With Docker already installed, the command to use is this: docker pull imiell/bash2py Next we can check how big that image is, with this command: docker images REPOSITORY TAG IMAGE ID CREATED SIZE imiell/bash2py latest 09dfc6f8a82e 5 years ago 494MB As we can see around half a GB of space is taken up by the Docker image. Let’s see bash2py in action by entering the container after asking Docker to run it: docker run -ti imiell/bash2py root@8c3fa65fce45:/opt/bash2py-3.5#

Script Python résultant

Maintenant que nous avons un simple script Bash, voyons ce que bash2py en fait. Nous allons utiliser l'approche de l'image Docker. Docker étant déjà installé, la commande à utiliser est la suivante :

docker pull imiell/bash2py

Ensuite, nous pouvons vérifier la taille de cette image, avec cette commande :

docker images

REPOSITORY TAG IMAGE ID CREATED SIZE imiell/bash2py latest 09dfc6f8a82e Il y a 5 ans 494MB

Comme nous pouvons le voir, environ un demi Go d'espace est occupé par l'image Docker.

Voyons bash2py en action en entrant dans le conteneur après avoir demandé à Docker de l'exécuter :

docker run -ti imiell/bash2py

root@8c3fa65fce45:/opt/bash2py-3.5#

As we can see from the command prompt, we’re inside the container and can execute commands relating to bash2py. Next, we’re going to use the “vi” text editor inside the container and paste the “bash.sh” script into a file of the same name on the container’s filesystem, with this command: root@8c3fa65fce45:/opt/bash2py-3.5# vi bash.sh Save that file inside the container by exiting “vi”. Now, run it too, if you like, with this command (after first making it executable again): root@8c3fa65fce45:/opt/bash2py-3.5# chmod +x bash.sh root@8c3fa65fce45:/opt/bash2py-3.5# ./bash.sh Great, the output is the same as before. We can count to five yet again. Let’s finally test bash2py with this command: root@8c3fa65fce45:/opt/bash2py-3.5# ./bash2py bash.sh

Comme nous pouvons le voir dans l'invite de commande, nous sommes à l'intérieur du conteneur et nous pouvons exécuter les commandes relatives à bash2py. Ensuite, nous allons utiliser l'éditeur de texte « vi » à l'intérieur du conteneur et coller le script « bash.sh » dans un fichier du même nom sur le système de fichiers du conteneur, avec cette commande :

root@8c3fa65fce45:/opt/bash2py-3.5# vi bash.sh

Sauvegardez ce fichier dans le conteneur en quittant « vi ».

Maintenant, exécutez-le, si vous le souhaitez, avec cette commande (après l'avoir d'abord rendu exécutable à nouveau) :

root@8c3fa65fce45:/opt/bash2py-3.5# chmod +x bash.sh

root@8c3fa65fce45:/opt/bash2py-3.5# ./bash.sh

Super, le résultat est le même qu'avant. Nous pouvons à nouveau compter jusqu'à cinq.

Testons enfin bash2py avec cette commande :

root@8c3fa65fce45:/opt/bash2py-3.5# ./bash2py bash.sh

The command completes without any output. If you do an “ls” command, you will see that a new file has been created inside the container’s directory called “bash.sh.py”, as so: ls MANIFEST README.txt analyzers bash-4.3.30 bash.sh bash.sh.py bash2py bash2py.py bin install source_code.txt tests If we use Python inside the container first, and execute that Python script, we should be able to see if it runs, as shown with this command: root@8c3fa65fce45:/opt/bash2py-3.5# python bash.sh.py I am a Bash script and I can count… 1 2 3 4 5 root@8c3fa65fce45:/opt/bash2py-3.5#

La commande se termine sans aucune sortie. Si vous faites une commande « ls », vous verrez qu'un nouveau fichier a été créé dans le répertoire du conteneur appelé « bash.sh.py », comme suit :

ls

MANIFEST README.txt analyseurs bash-4.3.30 bash.sh bash.sh.py bash2py bash2py.py bin install source_code.txt tests

Si nous utilisons d'abord Python à l'intérieur du conteneur, et que nous exécutons ce script Python, nous devrions pouvoir voir s'il s'exécute, comme le montre cette commande :

root@8c3fa65fce45:/opt/bash2py-3.5# python bash.sh.py

Je suis un script Bash et je peux compter…

1 2 3 4 5 root@8c3fa65fce45:/opt/bash2py-3.5#

Excellent! We have a working Python script! What has bash2py changed in our script? In the listing shown above, you can see the contents of our generated Python script. If you look at Listing Two, most of the work has been done setting up the script so it will run in the environment. At the end of the script, we can see a “for” loop, which is very Bash-like. The last thing to do is to copy the script outside the container and run it on my laptop, just to be sure. A reminder that when you type “CTRL-D” inside the container to exit the shell, your container will stop and destroy the data inside it, because of the Docker command we used earlier. With the Python script copied into my clipboard, I create a new script called “counter.py” and, knowing that my laptop is using Python version 3, then use this command to execute it. Delta ~ # python3 counter.py I am a Bash script and I can count… 1 2 3 4 5 As hoped, our simple script runs on my laptop too! Great news.

Excellent ! Nous avons un script Python qui fonctionne !

Qu'est-ce que bash2py a changé dans notre script ? Dans le listing ci-dessus, vous pouvez voir le contenu de notre script Python généré.

Si vous regardez le programme, la plupart du travail a été fait pour configurer le script afin qu'il s'exécute dans l'environnement. À la fin du script, nous pouvons voir une boucle « for », qui est très proche de Bash.

La dernière chose à faire est de copier le script en dehors du conteneur et de l'exécuter sur mon ordinateur portable, juste pour être sûr.

Je vous rappelle que lorsque vous tapez « CTRL-D » à l'intérieur du conteneur pour quitter le shell, votre conteneur s'arrête et détruit les données qu'il contient, à cause de la commande Docker que nous avons utilisée précédemment.

Avec le script Python copié dans mon presse-papiers, je crée un nouveau script appelé « counter.py » et, sachant que mon ordinateur portable utilise Python version 3, j'utilise ensuite cette commande pour l'exécuter.

Delta ~ # python3 counter.py

Je suis un script Bash et je peux compter…

1 2 3 4 5

Comme prévu, notre script simple fonctionne aussi sur mon ordinateur portable ! Bonne nouvelle.

The End Obviously you still need some knowledge about Python if you use tools like this. But bash2py could save you some eyestrain and lots of time under certain circumstances. Be warned you may find, especially for more complex operations, that a fair amount of tweaking is required. Hopefully, a quick look at this very clever tool has inspired you to try it out for yourself. You never know, it might save the day at some point in the future.

Fin

Il est évident que vous avez encore besoin de quelques connaissances de Python si vous utilisez des outils comme celui-ci.

Mais bash2py peut vous faire gagner de la fatigue visuelle et beaucoup de temps dans certaines circonstances. Attention, il se peut que vous trouviez, surtout pour les opérations les plus complexes, qu'une certaine quantité d'ajustements soit nécessaire.

Nous espérons qu'un rapide coup d'œil à cet outil très intelligent vous a donné envie de l'essayer par vous-même. On ne sait jamais, il pourrait vous sauver la mise à l'avenir.

issue184/tutoriel1.txt · Dernière modification : 2022/08/30 19:19 de auntiee