Friday, November 30, 2012

Utopie Python (ou realite?)

Utopia

Imaginez un monde ou on peut programmer en Python, ou que l'on veut. Oui, ca existe pour iPad, Android, iPhone, PC, Unix, Mac, Linux etc. Mais il reste un domaine....

Navigateurs Web


Ca serait genial si on n'avait pas a utiliser javascript. On mettrait dans notre page web, quelque chose du genre:


<script type="text/python">
for i in range(10):
    log(i)


</script>

Plutôt que quelque chose du genre:
<script type="text/javascript"> try{$ns}catch($err){$ns={0:{}}}
document.line_num=1
$Iterable1 =$assign(iter(range(int(10))))
while(true){
try{
    var $Next=next($Iterable1)
    i =$assign($Next)
    document.line_num=2
    log(i)
}catch(err0){
        if(err0.name=="StopIteration"){break}
    else{throw err0}
}
} </script>

Oui, ca serait genial, pas de doute. Mais bon il faut arreter de rever a cette utopie, quoi!

Vraiment?

Visitons Brython. C'est quoi?

Le code javascript ci-dessus a ete généré a partir du code Python, par Brython, un Python pour Browser (Navigateur).

On telecharge brython.js ici: brython/downloads et comment l'utiliser ici.

Allez voir cette page (http://www.brython.info/test/test_clock.html), ou vous y verrez une horloge analogique. Faites un view source sur cette page. Oui, c'est bien un programme en Python.

Oui, je sais... ça laisse sans parole...

Thursday, November 29, 2012

Matplotlib without an X server

Short form, by running xvfb-run python script.py

In a more detailed answer, you need to install xvfb first:

$ sudo apt-get install xvfb

And then, supposing a script like this that we save as mpl.py:

from matplotlib.pyplot import *

plot([2,4,2,5,6,3,1])
savefig("graph.png")

We then run it:

$ xvfb-run python mpl.py
 There should be a file named graph.png that will look like:

 All from the console.

Wednesday, November 28, 2012

Python sur Raspberrypi 01

Comme promis, apprenez Python. Et bien sur, on commence au commencement...

Pour les experts, il n'y a pas grand chose a voir. Mais si vous voyez continuellement une référence a Python dans vos recherches sur le Raspberry Pi, et vous vous demandez c'est quoi l'histoire, alors bienvenue a notre série de tutoriels sur le langage de programmation Python.

Sites

Alors tout d'abord, le site officiel pour le langage, c'est: python.org

Mais pour les francophones, il y a deux liens plus facile a utiliser, car tout en français:

wiki.python.org en français

wikipython.flibuste.net

Livres


Si vous débutez, il y a beaucoup d'options de livres sur Python en français.

Si vous préférez le papier, sur Amazon.fr, j'ai vu par exemple:
"Apprendre à programmer avec Python 3" de Gérard Swinnen et "Apprenez à programmer en Python" de Vincent Le Goff, ainsi que "Programmation Python" de Tarek Ziadé et Stefan Richter. Ils sont tous disponibles également en format Kindle.

Je doit dire que je n'en ai lu aucun des trois. J'ai lu "Think Python: How to think like a computer scientist" qui est la base du livre de Swinnen et il était bien. Aussi si quelqu'un veut recommander un autre livre sur Python en français, laissez le nous savoir en commentaire. Il y a une liste avec d'autres suggestions ici.

Livres gratuits


'Domptage de serpents pour les enfants', que j'ai deja mentionne sur mon blog. Apprendre à programmer avec Python (Python 2 ou 3) par Gérard Swinnen, oui, le même que le livre en papier chez Amazon. 
. Dive Into Python traduit en francais. Et il y a une traduction en ligne de A byte of python.

Python, le programme


Donc, Python est un langage de programmation, mais c'est aussi un programme exécutable. Il est inclus avec le Raspberry Pi et avec la majorité des systèmes de type Unix (Solaris, OpenIndiana, Mac OS/X et les varietes de Linux ). Il peut aussi être installé sous Windows, iPhone, iPad, Android etc. Pour cet article, je vais me référer au programme python en l’écrivant en caractères gras.

On peut utiliser python de plusieures manieres.

Le premier mode

Premièrement, de façon interactive sur la ligne de commande:


pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 


L’interprète de commande python est maintenant en attente d'une commande, d'avoir quelque chose a faire. On va donc lui demander d'imprimer (print) les mots "Bonjour, monde!". De la même façon que j'ai besoin de borner les mots avec des guillemets pour être clair sur ce qui va être imprimé, en Python on doit délimiter une chaine de caractères (une phrase) par des guillemets droits simple (') ou double (") de par et d'autre de cette chaine:

pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Bonjour, monde!"
Bonjour, monde!
>>>


python nous a répondu:
Bonjour, monde!

Vous pouvez l'essayer ici dans votre browser web: print "Bonjour,+monde!" (cliquer sur [ Forward >] pour faire executer le code)

Si notre chaine de caractères dépasse une ligne, alors il faudra utiliser ces guillemets droits simple ou double, trois fois de chaque cote ("""beaucoup de mots, donc ca risque d'etre multiligne""")


pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print """
... Bonjour, monde!
... Je continue.
... J'ai fini!
... """

Bonjour, monde!
Je continue.
J'ai fini!



python nous a répondu:
Bonjour, monde!
Je continue.
J'ai fini!

Par contre, nous, on commence a peine! Il est aussi bon de mentionner qu'une chaine de caractères entre triple guillemets ("""chaine de caractères""") d'elle même, sans instruction, est ce que l'on appelle une docstring, une chaine de caractères (ou phrase) de documentation. Un commentaire, en d'autres termes.

On peut aussi utiliser python comme une calculatrice:


pi@raspberrypi ~ $ python
Python 2.7.3rc2 (default, May  6 2012, 20:02:25) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 * 32
64


Pour quitter le programme python, on doit taper la commande: exit()

Le deuxième mode


Si notre code est bien court, il n'y a pas de problème a utiliser ce mode interactif. Mais, ça devient un peu lassant de réécrire le même code a chaque fois. On peut donc sauver notre code dans un fichier, auquel on donnera une extension .py et que l'on peut lancer encore et encore.

On va donc sauver notre programme qui imprime "bonjour, monde!" dans un fichier. Pour cela toutefois, il faut un éditeur de fichier. Pour les experts, je recommande scribes en mode graphique et vim en mode console (texte).

Comme on débute, je recommande plutôt d'installer geany:

 pi@raspberrypi ~ $ sudo apt-get install geany
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  geany-common
Suggested packages:
  doc-base
The following NEW packages will be installed:
  geany geany-common
0 upgraded, 2 newly installed, 0 to remove and 134 not upgraded.
Need to get 3,401 kB of archives.
After this operation, 8,682 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://mirrordirector.raspbian.org/raspbian/ wheezy/main
 geany-common all 1.22+dfsg-2 [2,336 kB]
Get:2 http://mirrordirector.raspbian.org/raspbian/ wheezy/main
 geany armhf 1.22+dfsg-2 [1,065 kB]
Fetched 3,401 kB in 6s (518 kB/s)                                              
Selecting previously unselected package geany-common.
(Reading database ... 91199 files and directories currently installed.)
Unpacking geany-common (from .../geany-common_1.22+dfsg-2_all.deb) ...
Selecting previously unselected package geany.
Unpacking geany (from .../geany_1.22+dfsg-2_armhf.deb) ...
Processing triggers for hicolor-icon-theme ...
Processing triggers for man-db ...
Processing triggers for menu ...
Processing triggers for desktop-file-utils ...
Setting up geany-common (1.22+dfsg-2) ...
Setting up geany (1.22+dfsg-2) ...
Processing triggers for menu ...
pi@raspberrypi ~ $ geany bonjour.py


On vient donc de lancer notre editeur. On tape notre code dans la fenetre bonjour.py:


Editeur de code Geany
On sauve, et on quitte (pour le moment, question de rester le plus simple possible).

Comment exécuter notre programme bonjour.py? Tres simplement:


pi@raspberrypi ~ $ python bonjour.py
Bonjour, monde!
pi@raspberrypi ~ $ 

C'est le deuxième mode d’opération, python exécutant un script.

Le troisième mode


Le troisième mode est disponible sur les ordinateurs de type Unix, et donc le Raspberry Pi. On relance notre éditeur geany:

pi@raspberrypi ~ $ geany bonjour.py 

On insere une nouvelle ligne 1
On sauve, et on quitte. La ligne que l'on vient d'ajouter indique quel programme va exécuter notre code. Ici, on indique python.

Mais, il faut aussi changer notre fichier du mode document, au mode executable, par l'entremise de la commande chmod:

pi@raspberrypi ~ $ chmod +x bonjour.py

On est maintenant prêt a lancer notre script:

pi@raspberrypi ~ $ ./bonjour.py
Bonjour, monde!
pi@raspberrypi ~ $

Par l'entremise de geany


Cela serait bien mieux si on pouvait rester dans notre éditeur, changer le code, l’exécuter, voir le résultat, continuer l’édition, l’exécuter, voir le résultat etc, sans avoir a quitter geany a chaque fois. On peut faire cela grace a la touche F5, ou du menu Build->Execute, ou encore le bouton avec les engrenages (View or Execute):

Bonjour, monde!
Ceci conclut notre premier tutoriel sur le langage Python. J’espère que cela vous aide.

Tuesday, November 27, 2012

Minecraft + Python + Raspberry Pi =



>>> Minecraft Raspberry Pi Edition (raspberrypi.org)

Python


#!/usr/bin/env python
import minecraft as mc

mc.connect()

for x in range(-10,10):
    for y in range(-10,1):
        for z in range(-10,10):
            mc.setblock(x, y, z, mc.GLASS)

Minecraft + Python + Raspberry Pi = ☺

Updating a local mercurial project

In the previous article, we cloned the pyptug repository from bitbucket. But what if the repository changes (and it did, this morning)?

Follow me


First, make sure you have signed up to bitbucket and follow the repository ( https://bitbucket.org/fdion/pyptug ). That way you will get an email notification when there is a change.

Solid Hg


Next, you need to go into the pyptug directory and issue:

 fdion@srv:~/bitbucket$ cd pyptug/  
 fdion@srv:~/bitbucket/pyptug$ hg incoming http://bitbucket.org/fdion/pyptug  
 warning: bitbucket.org certificate with fingerprint 24:9c:45:8b:9c:aa:ba:55:4e:01:6d:58:ff:e4:28:7d:2a:14:ae:3b not verified (check hostfingerprints or web.cacerts config setting)  
 real URL is https://bitbucket.org/fdion/pyptug  
 comparing with http://bitbucket.org/fdion/pyptug  
 searching for changes  
 changeset:  1:8e0c4e63bbb1  
 user:    fdion@bitbucket.org  
 date:    Mon Nov 26 09:52:46 2012 -0500  
 summary:   pep8 compliance  
 changeset:  2:638251f3f511  
 user:    fdion@bitbucket.org  
 date:    Mon Nov 26 10:39:57 2012 -0500  
 summary:   pep8 and fo3 fix  
 changeset:  3:b09297ef88b2  
 user:    fdion@bitbucket.org  
 date:    Mon Nov 26 10:43:09 2012 -0500  
 summary:   pep8 compliance  
 changeset:  4:9e0101cf03f8  
 user:    fdion@bitbucket.org  
 date:    Mon Nov 26 10:45:04 2012 -0500  
 summary:   pep8 compliance  
 changeset:  5:89aa2b01e1be  
 tag:     tip  
 user:    fdion@bitbucket.org  
 date:    Tue Nov 27 06:24:25 2012 -0500  
 summary:   Missing if __name__ ==  
 fdion@srv:~/bitbucket/pyptug$ hg pull http://bitbucket.org/fdion/pyptug  
 warning: bitbucket.org certificate with fingerprint 24:9c:45:8b:9c:aa:ba:55:4e:01:6d:58:ff:e4:28:7d:2a:14:ae:3b not verified (check hostfingerprints or web.cacerts config setting)  
 real URL is https://bitbucket.org/fdion/pyptug  
 pulling from http://bitbucket.org/fdion/pyptug  
 searching for changes  
 adding changesets  
 adding manifests  
 adding file changes  
 added 5 changesets with 9 changes to 9 files  
 (run 'hg update' to get a working copy)  
 fdion@srv:~/bitbucket/pyptug$ hg update  
 9 files updated, 0 files merged, 0 files removed, 0 files unresolved  

The hg incoming will basically tell us what the changes are, but will not download them. This is purely informational, you can skip that step if you want.

The hg pull command is what gets the changes to the pyptug repository pulled to your local machine.

Finally, hg update will apply those changes to a working copy. In the above example, 9 files have been changed over 5 changesets since I first published the repository.

Chchch...changes


If you are curious as to what was the change:

When running a web.py application through wsgi, and that means not only mod_wsgi or an external wsgi server, but also when running as python script.py [port] (since it will launch CherryPy), it is required to use:

if __name__ == "__main__":
to invoke app.run(). Else, it will lock itself by trying to open a socket on the same port twice.

hw2.py and hw3.py didn't have this. Although it did work in my automatic deployment test setup (uses cgi instead of wsgi so I can test every applications all at once), it didn't work in a standalone install.


Sunday, November 25, 2012

PYPTUG mercurial repository

A little experiment


web.py, the antiframework framework
I'm putting the code up before the actual talk (Monday, the 26th of November), for those who would like to follow along with their laptop. The code again is made available under an MIT license.

Assuming you already have mercurial:

$ hg clone https://bitbucket.org/fdion/pyptug

If you need to install mercurial first:

debian based
$ sudo apt-get install mercurial

or fedora
$ sudo yum install mercurial

Under solaris, it is available under the packagemanager. On windows or mac you can get it here: http://mercurial.selenic.com/

All those .py scripts and directories will make more sense during the talk, as we dig through them.

I will also post screencam captures later, for those who are not local.

Saturday, November 24, 2012

It's more fun to compute

last track  - "It's more fun to compute"


Ah, Computer World, by Kraftwerk. The last track is titled "It's more fun to compute". I'm thinking Hutter, Schneider and Bartos must have written this song in November, after raking and blowing leaves for a few days... All joking aside, I hope you have this album on your ipod.

So what is it exactly that makes computing more fun? More fun than what, I hear you ask... What do you think, is it more fun to compute?

Also, either tomorrow or Monday, I'll post the bitbucket Mercurial repository for the web.py presentation at PYPTUG that I'll be doing on Monday. In the interim, go ahead and install web.py. I have the instructions on the sidekick page. Basically:

pi@raspberrypi ~/Desktop $ sudo easy_install web.py
Searching for web.py
Best match: web.py 0.37
Processing web.py-0.37-py2.7.egg
web.py 0.37 is already the active version in easy-install.pth

Using /usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg
Processing dependencies for web.py
Finished processing dependencies for web.py


If you've gone through the PyHack workshop #01, you already installed mercurial (hg). If not, you will need to install it on your Raspberry Pi before you can get the code:


pi@raspberrypi ~/Desktop $ sudo apt-get install mercurial