![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
Python
Frequently-Asked Questions
J'utilise python depuis 2000. Et je suis encore surpris par la puissance de ce langage. C'est pourquoi, j'ai décidé d'ouvrir une FAQ Python, contenant quelques astuces, que j'ai trouvées surprenantes.
Pour plus d'information au sujet de cette faq, contactez Jean-Louis BICQUELET
FAQ Revised: mardi 27 août 2013 21:42:53
Lors du lancement d'un script python on obtient le message suivant:
sys:1: DeprecationWarning: Non-ASCII character '\xe0' in file D:\jlb_2008\pytho \regexp\exemple.py on line 15, but no encoding declared; see http://www.python. rg/peps/pep-0263.html for details
Pour supprimer ce message, il suffit dans les premières lignes du script d'ajouter un codage comme ceci:
# -*- coding: latin-1 -*-
Pour plus d'information consultez le site python.
from random import * print randint(1,6)
On redéfinit les constantes cout, cerr et nl et le tour est joué.
import sys class ostream: def __init__(self, file): self.file = file def __lshift__(self, obj): self.file.write(str(obj)); return self cout = ostream(sys.stdout) cerr = ostream(sys.stderr) nl = '\n' x=20 cout << x << nl
import locale import datetime locale.setlocale(locale.LC_ALL, 'fr_FR') now = datetime.datetime.now() now.strftime("%A %d %B %Y, %H:%M")
affichage:
'lundi 28 septembre 2009, 07:12'
Une autre façon de faire est d'utiliser le module time.
from time import strftime strftime(" %H:%M:%S %d/%m/%Y")
affichage:
'07:33:09 26/09/2009'
import datetime d=datetime.datetime(2010,11,2) print ((d - datetime.datetime(d.year,1,1)).days / 7) + 1 44
Deuxième méthode avec le module time:
import time from time import gmtime, strftime d = time.strptime("2 Nov 2010", "%d %b %Y") print(strftime("%U", d)) 44
stack=[] stack.append(5) stack.append(9) print stack.pop()+stack.pop() 14 print stack []
print (2+1j)*2 (4+2j) print (2+1j)+(3+3j) (5+4j) a=2+4j print a.real 2.0 print a.imag 4.0
- | dans le premier mais pas dans le second |
| | union |
& | intersection |
^ | dans un des ensemble mais pas les eux |
a=set(['chat','chien','poisson']) b=set(['elephant','girafe']) print a - b set(['chien', 'chat', 'poisson']) print a | b set(['chien', 'girafe', 'chat', 'poisson', 'elephant']) print a & b set([]) print a ^ b set(['chien', 'chat', 'poisson', 'girafe', 'elephant'])
>>>lines=["ligne1","ligne2"] >>>print lines ['ligne1', 'ligne2'] >>> lines=["ligne1","ligne2"] >>> for i in lines: ... print i ligne1 ligne2
>>> print len(lines) 2
Par exemple pour parcourrir une liste du premier à l'avant dernier élément on tapera:
>>> for i in xrange(len(lines)-1): ... print lines[i] ... ligne1
>>> lines.append("-------") >>> for i in xrange(len(lines)): ... print lines[i] ... ligne1 ligne2 -------
import sys,string class LtoH: def __init__(self): self.data=[] self.separator='=' def display(self): for href in self.data: keys = href.keys() keys.sort() for k in keys: print ' %s => %s' %(k,href[k]) def open(self,name): file=open(name) self.h= [] while 1: line=file.readline() if not line: break rec = {} for f in string.split(line): [key,value]=string.splitfields(f,self.separtor) rec[key]=value self.data.append(rec) t=LtoH() t.open('val.txt') t.display()
Le fichier est au format suivant:
nom=valeur a=test b=12 c=34213
Il est facile d'étendre les fonctions de cette classe.
Il est conseillé de définir la fonction __str__ qui permet afficher le contenu de la classe.
class point: def __init__(self,x,y): self.x=x self.y=y def __str__(self): return '(%s,%s) ' % (self.x, self.y) if __name__ == '__main__': p=point(3,7) print p
La fonction membre add ajoute un point dans cette liste. On voit ici un appel de fonction sur une variable de la classe.
Pour l'affichage des données de la classe, il faut boucler sur toute la liste pour concaténer dans une variable au format string et convertir les points à l'aide de lafonction str.
class segments: def __init__(self): self.list=[] def __str__(self): self.res="" for i in xrange(len(self.list)): self.res= self.res + str(self.list[i]) return self.res def add(self,p): self.list.append(p) if __name__ == '__main__': p1=point(3,7) p2=point(1,3) p3=point(7,6) s=segments() s.add(p1) s.add(p2) s.add(p3) print s
le résultat donne:
(3,7) (1,3) (7,6)
from string import repl_car=(('à','à'),('À','À'),('â','â'),('Â','Â'),('ä','ä'),('ã','ã'), ('é','é'),('É','É'),('è','è'),('È','È'),('ê','ê'),('Ê','Ê'),('ë','ë') ); m="Liste à modifier." for i in repl_car: [val,by]=i m=replace(m,val,by)
# -*- coding: iso-8859-1 -*- import string french = "je n'aime pas les accents é,è,à et je veux les faire disparaître." char_from = "éêàîêâ" char_to = "eeaiea" print french.traslate(string.maketrans(char_from,char_to))
Créez une classe qui utilise sgmllib de la manière suivante:
import sgmllib class Stripper(sgmllib.SGMLParser): def __init__(self): sgmllib.SGMLParser.__init__(self) def strip(self, some_html): self.theString = "" self.feed(some_html) self.close() return self.theString def handle_data(self, data): self.theString += data stripper = Stripper() print stripper.strip("""titre
Le retrait des tag est possible!
""")
On désire changer tous les textes entre * et * par les metatags html de mise en gras et tous ceux entre _ et _ par les metatags html de mise en italique.
On construit une expression régulière recherchant un mot ( \w+) ) entre deux *. Pour un * on doit utiliser l'antislash car il est lui même un caractère servant à définir les expressions régulières.
On utilise la méthode sub de l'expression construite pour effectuer la substitution.
Dans le cas du underscore ( _ ), il n'y a pas besoin d'antislash.
import re p = re.compile(r'\*(\w+)\*') m = p.sub(r'\1',"le texte est *important* lorsqu'il est en *gras* ou en _italique_.") p = re.compile(r'_(\w+)_') m = p.sub(r'\1',m) print m
le texte est important lorsqu'il est en gras ou en italique.
Les . doivent être backslashés. Les mots cherchés sont détectés grace à la méthode match. La méthode group retourne les éléments trouvés.
import re m='...[test ok]............' p = re.compile(r'\.\.\.\[(.*) (.*)]\.\.\.(.*)') r=p.match(m) if r: arg1=r.group(1) arg2=r.group(2)
import re line = "cat:chat,felin" line2= "cat chat" matchObj = re.match( r'(.*):(.*)', line, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: print "No match!!" matchObj = re.match( r'(.*):(.*)', line2, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: print "No match!!"
le group(1) retourne la premiere partie de la definition,
group(2) la deuxieme partie.
import re def remove_tags(s): return re.compile('<[^>]+>',re.S|re.I).sub('',s) s=""" <h1>texte</h1>Un vrai texte <b>html</b> avec des <i\>effets\</i> de style. Et il n'en reste rien! """ print remove_tags(s)
f = open('myfile.txt') lines = f.readlines() f.close() for line in lines: print line,
f = open('myfile.txt') line = f.readline() while line: print line, line = f.readline() f.close()Une autre manière de faire est:
with open("fichier.txt") as f: for line in f: print ("=>"+ line.rstrip()) f.close()
f = open('myfile.txt') for line in iter(f): print line, f.close()
def Fileread(filename): """ read a file into a string """ f = open(filename, 'r') s = f.read() f.close() return s
Utilisation par s=Fileread("texte.txt")
def Filewrite(filename, newValue): f = open(filename, 'w') f.write(newValue) f.close()
Utilisation par Filewrite("texte.txt",'mon texte à moi')
def Filecopy(oldFile, newFile): """ copy a file """ f1 = open(oldFile, "r") f2 = open(newFile, "w") while 1: text = f1.read(50) if text == "": break f2.write(text) f1.close() f2.close
def filtre(src,dst): "recopie un fichier en éliminant les lignes de remarques" fs = open(src, 'r') fd = open(dst, 'w') while 1: txt = fs.readline() if txt =='': break if txt[0] != '#': fd.write(txt) fs.close() fd.close() return
On peut modifier en fonction de ses besoins.
def Fileexists(filename): try: f = open(filename) f.close() return 1 except: return 0
import hashlib print hashlib.md5(open('jave5.jar','rb').read()).hexdigest() 604b750fc5ec34b8aeea22bf023f1b21
import os os.listdir("d:\\tmp") dirname = "c:\\" os.listdir(dirname) print [f for f in os.listdir(dirname) if os.path.isfile(os.path.join(dirname, f))] print [f for f in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, f))]
La seconde façon de faire, c'est d'utiliser glob qui permet un pattern matching sur le nom.
import glob glob.glob('c:\\tmp\\*.txt')
os.path.expanduser("~") 'C:\\Documents and Settings\\WBICQ'
import os os.chdir('/apps/was/server/logs')
import os print os.path.join("/tmp/", "mon_fichier.txt")
import os rep='.' print files
résultat:
['file.py', 'fileutil.py','fileutil.pyc', 'MEF.PL', 'mef2html.py', 'resub.py', 'test.html', 'test.mef', 'util.py']
Si vous désirez une sortie formatée:
for i in files: print i file.py fileutil.py fileutil.pyc MEF.PL mef2html.py resub.py test.html test.mef util.py
import popen2 (stdout, stdin, stderr) = popen2.popen3("dir c:") print stdout.readlines() [" Le volume dans le lecteur C s'appelle SYSTEM\n", ' Le num\x82ro de s\x82rie d u volume est 7CAB-1080\n', '\n', ' R\x82pertoire de C:\\\n', '\n', '16/01/2008 13:47Admin\n', '16/01/2009 13:08 Applicati on Data\n', '04/04/2008 10:17 40 AUTOEXEC.BAT\n', '16/01/2008 1 3:26 BMC\n', '05/11/2007 14:21 0 CONFIG.SYS\n ', '25/09/2009 10:13 cygnus\n', '09/07/2009 12:11 cygwin\n', '09/07/2009 14:05 cygwin_neo\n', '24/08/20 09 13:54 95 DEBUG.TXT\n', '16/01/2008 15:46 D ocuments and Settings\n', '17/04/2009 17:41 DownloadDirector\ n', '07/05/2008 16:34 Downloads\n', '14/01/2008 11:54 DRIVERS\n', '18/07/2008 15:05 103 DSHELTMP.BAT\n', '0 ...
import os for param in os.environ.keys(): print "%20s %s" % (param,os.environ[param])
sous Windows
GROUPBUR C:\Documents and Settings\Default User SYSTEMROOT C:\WINNT COMSPEC C:\WINNT\system32\cmd.exe TEMP C:\DOCUME~1\WBICQ\LOCALS~1\Temp PROCESSOR_ARCHITECTURE x86 ENVDON TR SIT_NOMHOTE techno NWUSERNAME WBICQ ALLUSERSPROFILE C:\Documents and Settings\All Users ENVIR WINNT SESSIONNAME Console HOMEPATH \ NWLANGUAGE English USER_NAME WBICQ USERNAME WBICQ SIT_NUMPORT 2000 MACHINE %login_name OS_VERSION V5.01 PROMPT $P$G LOGONSERVER \\C920001074 PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH LOCAL c:\usr\local FP_NO_HOST_CHECK NO WINDIR C:\WINNT APPDATA C:\Documents and Settings\WBICQ\Application Data HOMEDRIVE C: TYPP S SYSTEMDRIVE C: NOM WBICQ NUMBER_OF_PROCESSORS 2 STATION 001D091A1100 OS WINNT PROGRAMFILES C:\Program Files
import winsound winsound.PlaySound("c:\winnt\media\tada.wav",winsound.SND_FILENAME)
Par exemple pour Lancer 3 compteurs le code est:
import thread def counter(myid, count): for i in range(count): print '[%s] => %s' % (myid, i) for i in range(3): print thread.start_new(counter, (i, 30)) import time time.sleep(3) print 'exit Main thread'
Un autre exemple:
import thread, time def counter(myid, count): for i in range(count): time.sleep(1) print 'thread number %d reporting in at %d...' % (myid, time.clock()) print time.clock() thread.start_new(counter, (1, 3)) thread.start_new(counter, (2, 8)) time.sleep(10) print 'Exit main thread'
import socket print socket.gethostbyname(socket.gethostname())
affichage:
192.168.60.4
import ftplib session = ftplib.FTP('batman','root','secret') myfile = open('ftp.py','rb') session.storbinary('STOR ftp.py', myfile) myfile.close() session.quit()
import urllib f=urllib.urlopen("http://www.google.fr/").read()
Copyright (c) 2001-2009 Jean-Louis BICQUELET
This list of questions and answers was generated by makefaq.