frequently ask question python

Creation: 30 aout 2009
Mise à jour: 26 septembre 2009
Version: 1.1
Author: Jean-Louis Bicquelet-Salaün
Location: http://jlbicquelet.free.fr
Copyright: (c) 2009 Jean-Louis BICQUELET-SALAÜN
frequently ask question python

frequently ask question python

Creation: 30 aout 2009
Mise à jour: 26 septembre 2009
Version: 1.1
Author: Jean-Louis Bicquelet-Salaün
Location: http://jlbicquelet.free.fr
Copyright: (c) 2009 Jean-Louis BICQUELET-SALAÜN

Python Frequently-Asked Questions

I 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


Table of Contents

1. syntax
2. snippets
3. data
4. lists
5. strings
6. regular expression
7. files
8. system
9. sound
10. threads
11. net

1. syntax

1.1. How can I suppress the Non-ASCII character error message ?

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.


2. snippets

2.1. How can I throw a 6 faces dice ?
from random import *
print randint(1,6)


2.2. How can I use an output stream in a c++ way ?
You have to create a class stream. Then you overload the << operator. The name of the associated function is __lshift__.

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


2.3. How can I display the time and the date?
One can use datetime
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'



3. data

3.1. How can I create a stack in python ?
It's really easy. You just have to define a list and use the append() function to push data in the stack, and the pop() function to get data out of the stack.
stack=[]
stack.append(5)
stack.append(9)
print stack.pop()+stack.pop()
14
print stack
[]


3.2. How can I create a complex nimber class ?
It is useless! Python knows how to manage complex numbers.
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


3.3. How can I define set of items ?
You have to use the keyword set with an objects list. Operators are:

- 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'])



4. lists

4.1. How can I manipulate a list?
>>>lines=["ligne1","ligne2"]
>>>print lines
['ligne1', 'ligne2']

>>> lines=["ligne1","ligne2"]
>>> for i in lines:
...     print i
ligne1
ligne2


4.2. How can I know the size of a list?
>>> print len(lines)
2


4.3. How can I loop into a list by indexes ?
HYou just have to combine the xrange and len functions.

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


4.4. How can I append an item to the end of the list?
Use the function append.
>>> lines.append("-------")
>>> for i in xrange(len(lines)):
...     print lines[i]
...
ligne1
ligne2
-------



5. strings

5.1. How can replace multiples expressions ?
Use a list that will have an enumeration of the string to replace and the new value. Then make a loop.
from string import 

repl_car=(('à','à'),('À','À'),('â','â'),('Â','Â'),('ä','ä'),('ã','ã'),
('é','é'),('É','É'),('è','è'),('È','È'),('ê','ê'),('Ê','Ê'),('ë','ë')
);

m="Liste à modifier."
for i in repl_car:
         [val,by]=i
         m=replace(m,val,by)


5.2. how can I transcode characters (like the command tr) ?
# -*- 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))


5.3. How can I suppress html tags ?

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!

""")



6. regular expression

6.1. How can I seek a regular expression and to substitute it?

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.


6.2. How can I seek forr a sentence ?
One wishes to seek an expression of the type ...[mot1 mot2]............... Found words will be affected to variables to be re-used thereafter.

. 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)


6.3. How can I suppress html tags in a text?
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)




7. files

7.1. How can I read a text file ?
There are 3 ways to read a text file in python:
  1. reading all lines once:
    f = open('myfile.txt')
    lines = f.readlines()
    f.close()
    
    for line in lines:
        print line,
    
  2. reading file line by line. You can then read big files :
    f = open('myfile.txt')
    line = f.readline()
    while line:
        print line,
        line = f.readline()
    f.close()
    
  3. reading using an iterator:
    f = open('myfile.txt')
    for line in iter(f):
        print line,
    f.close()
    



8. system

8.1. How can I list the files of a directory ?
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


8.2. How can I get the resultat of a system command ?
You have to use popen3 after having imported popen2 module.
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:47              Admin\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
...


8.3. How can I list environment variables ?
environment variables are in the os.environ dictionnary.
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



9. sound

9.1. How can I play a soud under windows ?
import winsound
winsound.PlaySound("c:\winnt\media\tada.wav",winsound.SND_FILENAME)



10. threads

10.1. How can I launch multiple threads in python ?
Import the module thread. Use the method start_new with a pointer on the function and its parameters.

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'



11. net

11.1. How can I get my IP adress?
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.