Python
Frequently-Asked QuestionsI have been using python since 2000. And I am still surprises by the power of this language. That's the reason why, I decided to open a Python FAQ, containing some tips I have found.
For more information about this faq, please do contact Jean-Louis BICQUELET
FAQ Revised: Monday 28 September 2009 14:40:49
When the python script starts you will get the following message :
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
If you want to suppress this message, just add at the beginning of your script this line:
# -*- coding: latin-1 -*-
For more information please read python site.
from random import * print randint(1,6)
You have to redefine constants cout, cerr and nl and you can use it.
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")
display:
'lundi 28 septembre 2009, 07:12'
You can also use the time module.
from time import strftime strftime(" %H:%M:%S %d/%m/%Y")
display:
'07:33:09 26/09/2009'
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
- | in the first but not in the second |
| | union |
& | intersection |
^ | in one set but not in both sets |
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
For example, if you want to loop from the first element until the one before the last one you will type:
>>> for i in xrange(len(lines)-1): ... print lines[i] ... ligne1
>>> lines.append("-------") >>> for i in xrange(len(lines)): ... print lines[i] ... ligne1 ligne2 -------
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))
Create a class that uses sgmllib module that way:
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!
""")
One wishes to change all the texts between * and * by boldfacing HTML metatags and all those between _ and _ by italic HTML . One builds a regular expression scanning for a word (\w+) between two *. For a * one must use a backslash because it is a character used to define the regular expressions. The method sub is built to carry out substitution. In the case of an underscore (_), you don' need a backslash.
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.
. have to be backslashed. Word are detected by the match method. The group method returns founded elements.
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 def remove_tags(s): return re.compile('<[^>]+>',re.S|re.I).sub('',s) s="""texte
<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()
f = open('myfile.txt') for line in iter(f): print line, f.close()
import os rep='.' print files
result:
['file.py', 'fileutil.py','fileutil.pyc', 'MEF.PL', 'mef2html.py', 'resub.py', 'test.html', 'test.mef', 'util.py']
If you want to format the output :
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 cela donne
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())
display:
192.168.60.4
Copyright (c) 2001-2009 Jean-Louis BICQUELET
This list of questions and answers was generated by makefaq.