====== Python ====== * [[python_cheat_sheet]] * [[django]] * [[matplotlib]] * [[astuces_python|Astuces]] * [[PyCONFR 2010]] ===== Doc ===== * [[http://www.python.org/doc/current/|Doc python current]] (python.org) * [[http://docs.python.org/tutorial/index.html|Tutoriel officiel, très bien foutu]] * [[http://ginkobox.fr/docs/python-2.6.4-docs-html/|Doc python 2.6.4]] (local) * [[http://ginkobox.fr/docs/python-2.6.4-docs-html.tar.bz2|Télécharger Doc python 2.6.4]] (local, tar.bz2) * [[http://ginkobox.fr/docs/python-2.6.4-docs-html.zip|Télécharger Doc python 2.6.4]] (local, zip) * [[http://diveintopython.adrahon.org/|DiveIntoPython fr]] * [[http://python.developpez.com/cours/DiveIntoPython/php/frdiveintopython/toc/index.php|DiveIntoPython fr]] (developpez.com) ===== Basics ===== * [[http://docs.python.org/reference/simple_stmts.html|Simple statements]] (official doc) * [[http://docs.python.org/reference/compound_stmts.html|Compound statements]] (official doc) * [[http://docs.python.org/howto/unicode.html|HowTo Unicode]] (official doc) * [[http://docs.python.org/howto/index.html|HowTo's]] (official doc) ===== Interactive Shell ===== Python est livré de base avec un shell interactif très utile. Mais il peut être utile de l'améliorer en ajoutant des petites objets custom aux petits oignons ou encore en utilisant des shells alternatifs comme ipython. ==== Objets custom ==== Il est possible d'ajouter des objets au shell via la variable d'environnement ''PYTHONSTARTUP=chemin_vers_le_fichier_python''. Le namespace du shell contiendra alors tous les objets contenus dans le fichier indiqué. __Exemple__:def grep(pat, list, re=False): """Works on list of strings. When 're' argument is turned on, re.search is used instead of str.find.""" if re: import re def match(item): if re.search(pat, item): return True else: return False else: def match(item): if item.find(pat) >= 0: return True else: return False for item in list: if match(item): print item NB: Ipython ne tient pas compte de ''PYTHONSTARTUP''. Pour charger des trucs custom, voir ipythonrc. ==== Ipython ==== Ipython est un shell interactif amélioré (coloration syntaxique, historique inter-instances, auto-complétion et autre goodies). === Cygwin === Pour lancer ipython sur Cygwin, taper simplement ''ipython'' dans le prompt causera une erreur ''bash: ... /usr/bin/python : Bad interpreteur : Permission Denied''. La solution la plus simple consiste à préférer ''ipython.bat'' pour lancer ipython. Un alias dans le .bashrc de cygwin permet de retrouver un jolie syntaxe. === ipythonrc === Valable pour iptyhon 0.10 Ipython possède un système de fichiers de configuration à la UNIX. Dans la version 0.10, éditer ''ipy_user_conf.py'' situé dans le répertoire ''.ipython'' dans le $HOME. Pour charger utiliser le ''PYTHONSTARTUP'', on peut y ajouter: def import_pystartup(): """Import custom function in shell from PYTHONSTARTUP. PYTHONSTARTUP is a environnement variable shared among different python shells.""" import os filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): # execfile(filename) # Can't use builtin execfile function in ipython... execf(filename) sans oublier d'appeler cette fonction dans le ''main''. ===== Unicode ===== * [[http://docs.python.org/howto/unicode.html|HowTo]] (official doc) * [[http://docs.python.org/library/codecs.html|Codecs]] ===== RegExp ===== * [[http://diveintopython.adrahon.org/regular_expressions/index.html]] * [[http://www.amk.ca/python/howto/regex/regex.html]] ===== PyGTK ===== * [[http://www.pygtk.org/]] * [[http://python.developpez.com/cours/pygtktutorial/php/pygtkfr/index.php|Cours developpez.com]] * [[http://www.siteduzero.com/tutoriel-3-93860-pygtk.html|Cours site du zéro]] * [[http://daniel.coquette.free.fr/dotclear/index.php/post/2006/12/11/Creer-des-interfaces-graphique-avec-PyGTK-et-Glade|PyGTK + Glade]] * [[http://pinard.progiciels-bpi.ca/notes/GTK,_pygtk_et_Glade.html|Autre PyGTK + Glade]] ===== Tkinter ===== * [[http://sebsauvage.net/python/gui/index_fr.html|Tuto]] * [[http://docs.python.org/library/tkinter.html|Doc Python]] * [[http://effbot.org/zone/tkinter-index.htm|Unofficial doc]] ===== WxWidget ===== * [[http://sebsauvage.net/python/gui/index_fr.html|Tuto WxWidget/Tkinter]] * [[http://www.zetcode.com/wxpython/thetetrisgame/|Tetris game]] ===== Threading ===== * [[http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/|Basic threading tuto]] * [[http://code.activestate.com/recipes/82965-threads-tkinter-and-asynchronous-io/|Thread, Tkinter and asynchornous IO]] * [[http://docs.python.org/library/queue.html|Queues implementation in Python]] * [[http://effbot.org/zone/tkinter-threads.htm|Threads + Tkinter]] * [[http://www.wellho.net/solutions/python-python-threads-a-first-example.html|Python threads exemple]] * [[http://docs.python.org/library/threading.html|Doc Python]] ===== Advanced Python ===== * [[http://www.siteduzero.com/tutoriel-3-33509-pratiques-avancees-et-meconnues-en-python.html|Manipulation avancée des listes]] * [[http://www.ledeveloppeur.com/2009/05/25/decorateur-en-python/|Le décorateur]] (explication compréhensible, rare sur le web) * [[http://docs.python.org/howto/sorting.html|Sorting]] (official doc) * [[http://doc.ubuntu-fr.org/ipython|IPython, le python shell improved]] * [[http://python.developpez.com/cours/DiveIntoPython/php/frdiveintopython/power_of_introspection/and_or.php|L'astuce and/or]] * [[http://www.siafoo.net/article/56|Type checking in Python]] ===== Best practices ===== * [[http://www.canonical.org/~kragen/isinstance/|Do not use isinstance()]] ===== Programmation événementielle ===== * [[http://en.wikipedia.org/wiki/Twisted_%28software%29|Twisted]] (framework réseau, supporte de nombreux protocoles) * [[http://www.gevent.org/|Gevent]] (framework réseau également, supporte moins de choses, mais plus léger que Twisted) * [[http://code.google.com/p/gevent/wiki/ProjectsUsingGevent|Projets basés sur Gevent]] * [[http://bitbucket.org/denis/gevent/src/tip/examples/concurrent_download.py#cl-4|Exemple simple d'utilisation de Gevent]] ===== Profilage, optimisation et performances ===== * [[python_tuning|Tuning python]] ===== Recipes ===== * [[http://code.activestate.com/recipes/577267-xml-to-python-data-structure-de-serialization/?in=lang-python|XML to Python data de-serialization]] * [[http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/|Ajouter des séparateurs de milliers à des nombres formattés]] * [[http://code.activestate.com/recipes/577459-convert-a-youtube-transcript-in-srt-subtitle/?c=15695| Convert a youtube transcript in srt subtitle]] #!/usr/bin/python # -*- encoding:utf-8 -*- """Translate Google's Transcript into srt file. Takes google's transcript filename as argument (xml extension required). NB: to get google's transcript, use tihs URL: http://video.google.com/timedtext?lang=en&v=VIDEO_ID """ # srt example """1 00:00:20,672 --> 00:00:24,972 Entre l’Australia et la South America, dans l’Océan South Pacific…""" # Google's transcript example (first tags) """ This is a matter of National Security.""" import re, sys # Pattern to identify a subtitle and grab start, duration and text. pat = re.compile(r'(.*)?') def parseLine(text): """Parse a subtitle.""" m = re.match(pat, text) if m: return (m.group(1), m.group(2), m.group(3)) else: return None def formatSrtTime(secTime): """Convert a time in seconds (google's transcript) to srt time format.""" sec, micro = str(secTime).split('.') m, s = divmod(int(sec), 60) h, m = divmod(m, 60) return "{:02}:{:02}:{:02},{}".format(h,m,s,micro) def convertHtml(text): """A few HTML encodings replacements. &#39; to ' &quot; to " """ return text.replace('&#39;', "'").replace('&quot;', '"') def printSrtLine(i, elms): """Print a subtitle in srt format.""" return "{}\n{} --> {}\n{}\n\n".format(i, formatSrtTime(elms[0]), formatSrtTime(float(elms[0])+float(elms[1])), convertHtml(elms[2])) fileName = sys.argv[1] def main(fileName): """Parse google's transcript and write the converted data in srt format.""" with open(sys.argv[1], 'r') as infile: buf = [] for line in infile: buf.append(line.rstrip('\n')) # Split the buffer to get one string per tag. buf = "".join(buf).split('><') i = 0 srtfileName = fileName.replace('.xml', '.srt') with open(srtfileName, 'w') as outfile: for text in buf: parsed = parseLine(text) if parsed: i += 1 outfile.write(printSrtLine(i, parsed)) print('DONE ({})'.format(srtfileName)) if __name__ == "__main__": main(fileName) ===== Advocacy ===== * [[http://luxor-xul.sourceforge.net/talk/jug-feb-2003/slides.html|Présentation de Luxor-XUL]], qui comprends un plaidoyer pour Python assez synthetic * [[http://docs.python.org/howto/advocacy.html|Python Advocacy HowTo]] (from official doc) ===== ErrorMsg ===== * re: * ''sre_constants.error: invalid group reference'' [[http://mail.python.org/pipermail/tutor/2005-September/041214.html|Soultion]] (group substitution: ''\g<1>'') ===== Common Bad Programming Pattern ===== ==== Référence à un objet ==== Lorsque l'on fait un assignement sur un objet, Python réalise une copie par référence (sorte de pointeur, hard link). Tout assignement sur le nouveau nom affecte naturellement le premier nom puisqu'ils référencent le même objet. class A(): c = 1 a = A() b = a b.c = 2 # a.c returns 2 d = A.c e = d e = 2 # d.c returns 1 Cependant, lorsque l'on fait un assignement sur un attribut d'un object, le nom vient référencer la valeur retournée par l'attribut. L'assignement d'une nouvelle valeur ne modifira pas la valeur de l'attribut de l'objet. Cela se comprend facilement: a = A() >>> a # returns (la référence) b = a.c >>> b # returns 1 (la valeur) Pour référencer l'attribut d'un objet, utiliser getattr (super puissant!) f = getattr(a, "c") ===== Cool Stuff ===== * [[http://www.kellyrob99.com/blog/2010/03/14/breaking-weak-captcha-in-slightly-more-than-26-lines-of-groovy-code/|Breaking weak captcha simply]]