17.12.2012 Views

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

Programmation PYTHON - Zenk - Security - Repository

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Bonnes pratiques et optimisation du code<br />

CHAPITRE 13<br />

L’exemple ci-dessous exécute une fonction dans un thread séparé et laisse le thread<br />

principal libre. Ce dernier en l’occurrence attend que le thread annexe s’achève, en<br />

affichant des caractères sur la sortie standard.<br />

Exemple 1<br />

#!/usr/bin/python<br />

# -*- coding: utf8 -*from<br />

threading import Thread<br />

from time import sleep<br />

from sys import stdout<br />

def visiteur():<br />

print("C'est André, je monte !")<br />

sleep(5)<br />

print('\ntoc toc toc')<br />

if __name__ == '__main__':<br />

print("Drrrrrrring")<br />

sleep(1)<br />

print('Oui ?')<br />

sleep(1)<br />

thread = Thread(target=visiteur)<br />

thread.start()<br />

sleep(1)<br />

print('OK, dépêche toi')<br />

[...]<br />

i = 0<br />

while thread.isAlive():<br />

if i == 0:<br />

stdout.write('z')<br />

i = 1<br />

else:<br />

stdout.write('Z')<br />

i = 0<br />

stdout.flush()<br />

sleep(0.4)<br />

print("Ah, te voilà ! J'ai bien failli attendre !")<br />

$ python threaded.py<br />

Drrrrrrring<br />

Oui ?<br />

C'est André, je monte !<br />

455

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!