Différences entre les versions de « Aide mémoire d'Arthur pour l'utilisation de Python »

De Wikip
toross>WikiAdmin
m (1 version importée)
 
(2 versions intermédiaires par 2 utilisateurs non affichées)
Ligne 5 : Ligne 5 :
}}
}}


== Précédence des opérateurs ==
== Priorité des opérateurs (precedence) ==
{{parW|
{{parW|1=
* [https://docs.python.org/2/reference/expressions.html#operator-precedence docs.python.org]
Par oredre croissante :
* {{m|1=lambda}}
*: Lambda expression
* {{m|1=if}}  {{m|1=else}}
* {{m|1=or}}
* {{m|1=and}}
* {{m|1=not}} x
* {{m|1=in}}, {{m|1=not in}}, {{m|1=is}}, {{m|1=is not}}, {{m|1=<}}, {{m|1=<=}}, {{m|1=>}}, {{m|1=>=}}, {{m|1=<>}}, {{m|1=!=}}, {{m|1===}}
*{{m|1={{!}}}}
*: Bitwise OR
* {{m|1=^}}
*: Bitwise XOR
* {{m|1=&}}
*: Bitwise AND
* {{m|1=<<}}, {{m|1=>>}}
*: Shifts
* {{m|1=+}}, {{m|1=-}}
* {{m|1=*}}, {{m|1=/}}, {{m|1=//}}, {{m|1=%}}
* {{m|1=+x}}, {{m|1=-x}}, {{m|1=~x}}
*: Positive, negative, bitwise NOT
* {{m|1=**}}
*: Exponentiation
* x{{m|1=[}}index{{m|1=]}}, x{{m|1=[}}index{{m|1=:}}index{{m|1=]}}, x{{m|1=(}}arguments...{{m|1=)}}, x{{m|1=.}}attribute
*: Subscription, slicing, call, attribute reference
* {{m|1=(}}expressions...{{m|1=)}}, {{m|1=[}}expressions...{{m|1=]}}, {{m|1={}}key{{m|1=:}} value...{{m|1=} }}, {{m|1=`}}expressions...{{m|1=`}}
*: Binding or tuple display, list display, dictionary display, string conversion
[https://docs.python.org/2/reference/expressions.html#operator-precedence docs.python.org]
}}
}}
== Système et codage das chaînes de caractères ==
 
== Les types ==
=== Les constantes ===
{{parW|1=
{{parW|1=
Parfois le codage avec le système a des problèmes :
* [https://peps.python.org/pep-0008/#constants PEP 8 – Style Guide for Python Code]
{{code|colNb=80|lang=python|code=
* [https://github.com/simon-ritchie/pconst/blob/master/README.md pconst(simon-ritchie)]
print(sys.getdefaultencoding())
* [https://github.com/hmeine/named_constants/blob/master/README.rst named_constants(hmeine)]
print(sys.stdout.encoding)
* [https://docs.python.org/3/library/typing.html#typing.Final typing.Final]
* ★[https://blog.finxter.com/python-enum-get-value-five-best-methods Enum Get Value – Five Best Methods]
* ★★★ [https://docs.python.org/3/library/enum.html enum]
}}
}}
{{code|colNb=80|lang=python|code=
{{parW|1=
#!/usr/bin/python
{{code|lang=python||code=
# -*- coding: UTF-8 -*-
class indCont(IntEnum):
    @classmethod
    def nm( name, defVal=None):       
        return getattr( name , defVal )
 
class gbI(indCont):
    dH            = 0  # gbI.dH deltaHeight
    dT            = 1  # gbI.dT
    dTcMax        = 2  # gbI.dTcMax
    dWaterFlowMax  = 3  # gbI.dWaterFlowMax
    dl            = 4  # gbI.dl
    upLevel        = 5  # gbI.upLevel
    downLevel      = 6  # gbI.downLevel
    wettedLength  = 7  # gbI.wettedLength
    dryLength      = 8  # gbI.dryLength
    emergedLength  = 9  # gbI.emergedLength  -> flt.emergedLength
    immergedLength = 10 # gbI.immergedLength -> flt.immergedLength
    filterFlow    = 11 # gbI.filterFlow -> flt.waterFlow
    imFlow        = 12 # gbI.imFlow -> flt.imFlow
    emFlow        = 13 # gbI.emFlow -> flt.emergedFlow
    wetTc          = 14 # gbI.wetTc -> flt.wettedTc


print( "OS encoding : ", locale.getpreferredencoding())
if __name__ == '__main__':
}}
    #---------------------------------------------------------------------------
Pour python3 :
    print( gbI )
{{code|colNb=80|lang=python|code=
    print( list(gbI) )
def printRaw( *text ):
    print( "dT", gbI( gbI.dT) )
     myout = open(1, "w", encoding = "UTF-8", closefd = False)
    print( "downLevel", getattr( gbI, "downLevel" , None ))
     print(*text, file=myout)
     print( "immergedLength", gbI.nm( "immergedLength") )
     myout.flush()
     print( gbI.dH.name, gbI.dH )
     myout.close()
     print( gbI.dT.name, gbI.dT )
     try :
        gbI.dH = 4
    except AttributeError as err :
        print(err)
}}
}}
}}
}}


== Programme ==
=== Les dates ===
=== Versionnement ===
==== git/pythonTool/pattern.py ====
==== Application ====
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|lang=python|code=
################################################################################
#-------------------------------------------------------------------------------
# release.V1.V2.V3.V4
import time # https://docs.python.org/fr/3/library/time.html#time.gmtime
# release x(n), rpa, ra, rb, rc(n), rl :
# L'epoch est le point de départ du temps, le résultat de time.gmtime(0) est
#         x(n) : x1 x2 , x3 ... x400 ... (in development)
# le 1er janvier 1970 à 00:00:00
#         rpa  : Release Pre-Alpha for unit or intergation tests
#-------------------------------------------------------------------------------
#        ra  : release alpha final tests in development team "recette usine"
def getTimeAsFloat() :
#         rb  : release beta test in client test team "recettes métier"
    return time.time() # absolue time in seconds
#        rc(n): release candidate 1, 2, 3, ... test in client test team
#-------------------------------------------------------------------------------
#         rl  : release live "live release" or gd (gold) or pr (prod)
def getTimeAsStr( fmt ):
#  
    return time.strftime("%Y/%m/%d_%H:%M:%S",fmt)
#         V1 : architecture modification
#-------------------------------------------------------------------------------
#        V2 : function modifications
timeSec = getTimeAsFloat()              # time in seconds
#        V3 : implementation of functions
gmtTime = time.gmtime( timeSec )       # gmt Greenwich Mean Time
#        V4 : bug corrections
                                        # (Temps moyen de Greenwich)
VERSION = "x1-0.0.0.0"
locTime = time.localtime( timeSec )     # local time
################################################################################
#-------------------------------------------------------------------------------
APP_PATH, APP_NAME = os.path.split(__file__)
print( "(s) time", timeSec )
print( "gmt time", getTimeAsStr( gmtTime ) )
print( "loc time", getTimeAsStr( locTime ) ) 
}}
{{code|lang=text|code=
(s) time 1734213182.5401628
gmt time 2024/12/14_21:53:02
loc time 2024/12/14_22:53:02
}}
}}
}}
}}
==== Library ====
==== get_datetime_str ====
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
<source lang="python">
#!/usr/bin/python
def get_datetime_str():
# -*- coding: UTF-8 -*-
    return time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
################################################################################
</source>
# API identification file with list of interface published and accessible items.
 
################################################################################
<source lang="python">
# module identification file with api sub module.
def get_date_year( date ):
#
     return time.strftime("%Y",date)
# [release-]current.revision.age
 
#
def get_date_month( date ):
# [release-]apiVersion.revisionOfThisVersion.ageOfThisApi
    return time.strftime("%m",date)
#
 
# exemple : 3.1.2
def get_date_day( date ):
#            if you use API 1.x.x you can use it : 3-2=1
    return time.strftime("%d",date)
# current :
</source>
#        interface, API version
# revision:
#        implementation of API version
# age     :
#        ascendant compatibility between API
#        versions compatible width API : current, current-1, ...(current - age)  
#
# release x(n), rpa, ra, rb, rc(n), rl :
#        x(n) : x1 x2 , x3 ... x400 ... (in development)
#        rpa  : Release Pre-Alpha for unit or intergation tests
#        ra  : release alpha final tests in development team "recette usine"
#        rb  : release beta test in client test team "recettes métier"
#        rc(n): release candidate 1, 2, 3, ... test in client test team
#        rl  : release live "live release" or gd (gold) or pr (prod)
VERSION = "x1-0.0.0"
ABSTRACT_MSG="call of abstract method"
}}
}}
}}
 
==== date_str2date_float ====
=== En-tête ===
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
<source lang="python">
#!/usr/bin/python
def date_str2float( sdate ):
# -*- coding: UTF-8 -*-
    ds = time.strptime( sdate,"%d/%m/%Y"  )
    d = time.mktime( ds )
    return d
</source>
}}
}}
}}
==== date_float2date_str ====
 
=== main ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang=python|code=
<source lang="python">
if __name__ == '__main__' :   
def date_float2date_str( d ):
     pass
    ds = time.strftime("%d/%m/%Y", time.gmtime(d) )
     return ds
</source>
}}
}}
}}
==== date_float_add_days ====
 
=== minmal ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang=python|code=
<source lang="python">
#!/usr/bin/python
def date_float_add_days( d, nb ):
# -*- coding: UTF-8 -*-
    nd = d + 3600*24*nb
import os, sys, re
     return nd
 
</source>
if __name__ == '__main__' :   
     pass
}}
}}
}}
 
==== time2str str2time getAcTimeOfFile timeToFile fileToTime ====
=== Exception, raise, try ===
{{parW|1=
{{parW|1=
{{cadreR|1=
{{code|colNb=70|lang=python|code=
Lire d'abord [[#goodWay|La bonne façon de gérer les exceptions]]
timeForat = "%Y-%m-%d_%H-%M-%S"
}}
def time2str( t=None ):
    st = time.localtime( t )
    return time.strftime( timeForat , st )
def str2time( text ) :
    st = time.strptime( dT, timeForat )
    return time.mktime( st )
def getAcTimeOfFile( filename ):
    infoStat = os.stat( filename )
    st = time.localtime( infoStat.st_atime )
    t = time.mktime( st )
    return t
def timeToFile( filename, t ):
    dT = time2str( t )
    tofile( filename, dT )
def fileToTime( filename ):
    dt = fromfile( filename )
}}
}}
==== solution élégante pour tracer et informer ====
{{parW|1=
Exemple  d'utilisation
{{code|lang=python|code=
    def debugInfo( pm ):
        global debugIndex
        traceback.format_stack()
        # frame,filename, num, func = inspect.getouterframes(
        #                                    inspect.currentframe())[1][:4]
        debugIndex += 1
        print("")
        print("id(pm)", id(pm) )
        print("debugIndex",debugIndex)
        for ll in traceback.format_stack()[:-1] :
            print( "    "+ll )
        print(pm)
        print("%s" %(pm.onGetInfo))
        print("%s %s" %(pm.pressureDropMaxTime, pm.pressureDropMax ))
        print("Enter");input()
}}
}}


{{code|lang=python|code=
== Système et codage das chaînes de caractères ==
import traceback
{{parW|1=
import sys
Parfois le codage avec le système a des problèmes :
from testLib import exceptionProcess
{{code|colNb=80|lang=python|code=  
               
print(sys.getdefaultencoding())
def myFunction2( a ):
print(sys.stdout.encoding)
    myFunction( a )
 
class MyClass :
    def __init__(self,a):
        self.a = a
    def do(self):
        try :
            a = self.a / 0           
        except Exception as err :
            errMsg = exceptionProcess(err, sys.exc_info(),
                                                    traceback.format_stack() )
            print(errMsg)
            exit(1)
       
def myFunction( a ):
    cl = MyClass(a)
    cl.do()
    print("End of myFunction")       
       
if __name__ == '__main__' :
    pass
    myFunction2( 3 )
}}
}}
 
{{code|colNb=80|lang=python|code=
 
{{code||lang=python|code=
#!/usr/bin/python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
import inspect
 
import traceback
print( "OS encoding : ", locale.getpreferredencoding())
################################################################################
}}
def exceptionProcess(err, exeInfo, lastStack ):
Pour python3 :
    """
{{code|colNb=80|lang=python|code=
import sys
def printRaw( *text ):
import traceback
     myout = open(1, "w", encoding = "UTF-8", closefd = False)
import inspect
     print(*text, file=myout)
   
     myout.flush()
use :
     myout.close()
errMsg = exceptionProcess(err, sys.exc_info(), traceback.format_stack() )
"""   
    frame,filename, num, func = inspect.getouterframes(
                                            inspect.currentframe())[1][:4]   
     last = traceback.format_list(traceback.extract_tb(exeInfo[2]))[0]
    history = lastStack
    txt = ""
    for x in history[:-1] :
        txt += x
     txt += last
     txt += "catched p:%s\nline:%s func:%s\n" % (filename, num, func)  
     txt += "ERROR " + str(err)  
    return txt
################################################################################
}}
}}
}}
}}


==== Obtenir nom de fichier, numéro de ligne et nom de fonction ====
== Programme ==
===== Cas simple mais non utile =====
=== Versionnement ===
==== Obtenir la signature numérique (hashage sha) du versionnement par git ====
===== subprocess.check_output - git describe or git show =====
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|lang=python|code=
import inspect
def getVersionningSignature(  ):
    try :
        # label = "-"+subprocess.check_output(["git", "describe"]).strip(
        # ).decode('utf-8')
        sign = "_sha_"+subprocess.check_output(
                            ["git", "show","-s","--format=%h"]).decode('utf-8')   
    except FileNotFoundError as err :
        sign = "".encode('utf-8')
    return sign.strip()
}}
}}
===== subprocess.check_output - git rev-parse HEAD =====
{{parW|1=
{{code|lang=python|code=
import subprocess
def get_git_revision_hash() -> str:
    return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip()


raisehead = "Error in %s:%s:%s\n" %inspect.getframeinfo(inspect.currentframe())[:3]
def get_git_revision_short_hash() -> str:
raise xmlBaseError("%sNo valid cardinality=%s for node named grammar in grammar" %(raisehead,node_nb))
    return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip()}}
}}
}}
}}


===== Obtenir nom de fichier, numéro de ligne et nom de fonction de l'appelant  =====
===== gitpython =====
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|lang=bash|code=
class xmlBaseError( Exception ) :
pip install gitpython
    def __init__(self, value):
}}
        frame,filename, num, func = inspect.getouterframes(inspect.currentframe())[1][:4]
{{code|lang=python|code=
        path, name = os.path.split(filename)
import git
        head="%s:%s:%s\n    " % ( name, num, func)
repo = git.Repo(search_parent_directories=True)
        self.value = head+value
sha = repo.head.object.hexsha
    def __str__(self):
        return self.value
}}
}}
}}
}}
==== Un exemple simple pour tout exceptions en affichant la trace ====
 
==== Application ====
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|colNb=70|lang=python|code=
#!/usr/bin/env python
################################################################################
 
# release.V1.V2.V3.V4
try :
# release x(n), rpa, ra, rb, rc(n), rl :
    raise ...
#        x(n) : x1 x2 , x3 ... x400 ... (in development)
 
#        rpa  : Release Pre-Alpha for unit or intergation tests
except SomeException as err:
#        ra  : release alpha final tests in development team "recette usine"
    errtrbk = traceback.format_exc()
#        rb  : release beta test in client test team "recettes métier"
    print "ERROR:\n%s\%s" %(str(err),errtrbk))
#        rc(n): release candidate 1, 2, 3, ... test in client test team
 
#        rl  : release live "live release" or gd (gold) or pr (prod)
    print u"MyException raised", e.__class__.__name__, e
#
else :
#        V1 : architecture modification
    print u"Unkown exeption :"
#        V2 : function modifications
#        V3 : implementation of functions
#        V4 : bug corrections
VERSION = "x1-0.0.0.0"
################################################################################
APP_PATH, APP_NAME = os.path.split(__file__)
}}
}}
}}
}}
==== Un exemple avec importation ====
==== Library ====
{{parW|1=
{{parW|1=
exception_test.py  :
{{code|colNb=70|lang=python|code=
{{code|colNb=70|lang=python|code=
class MyException( Exception ) :
#!/usr/bin/python
    pass
# -*- coding: UTF-8 -*-
}}
################################################################################
fonctions.py :
# API identification file with list of interface published and accessible items.
{{code|colNb=70|lang=python|code=
################################################################################
from exception_test import MyException
# module identification file with api sub module.
 
#
def f() :
# [release-]current.revision.age
    raise MyException(u"test")
#
# [release-]apiVersion.revisionOfThisVersion.ageOfThisApi
#
# exemple : 3.1.2
#            if you use API 1.x.x you can use it : 3-2=1
# current :
#        interface, API version
# revision:
#        implementation of API version
# age    :
#        ascendant compatibility between API
#        versions compatible width API : current, current-1, ...(current - age)
#
# release x(n), rpa, ra, rb, rc(n), rl :
#        x(n) : x1 x2 , x3 ... x400 ... (in development)
#        rpa  : Release Pre-Alpha for unit or intergation tests
#        ra  : release alpha final tests in development team "recette usine"
#        rb  : release beta test in client test team "recettes métier"
#        rc(n): release candidate 1, 2, 3, ... test in client test team
#        rl  : release live "live release" or gd (gold) or pr (prod)
VERSION = "x1-0.0.0"
ABSTRACT_MSG="call of abstract method"
}}
}}
}}
raise.py :
 
=== En-tête ===
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|colNb=70|lang=python|code=
#!/usr/bin/env python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
}}
}}


from exception_test import MyException
=== main ===
from fonctions import f
{{parW|1=
 
{{code|colNb=80|lang=python|code=
try :
if __name__ == '__main__' :   
    f()
    pass
except MyException,e :
    print u"MyException raised", e.__class__.__name__, e
else :
    print u"Unkown exeption"
}}
 
Résultats :
{{code|colNb=70|lang=text|code=
MyException raised MyException test
}}
}}
}}
}}


=== Options en ligne de commande ===
=== minmal ===
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|colNb=80|lang=python|code=
#!/usr/bin/python
#!/usr/bin/python
# -*- coding: ISO8859-1 -*-
# -*- coding: UTF-8 -*-
import os, sys, re


import os,sys, getopt
if __name__ == '__main__' :   
    pass
}}
}}


################################################################################
=== Exception, raise, try ===
# Help
{{parW|1=
################################################################################
{{cadreR|1=
def help() :
Lire d'abord [[#goodWay|La bonne façon de gérer les exceptions]]
    print u"""\
}}
Help on %(app)s :
}}
-------------------    
==== solution élégante pour tracer et informer ====
%(app)s -x -x AAA --XXXX --XXXX AAAA 
{{parW|1=
    -h :
Exemple  d'utilisation
         print this help
{{code|lang=python|code=
    """ % ({"app":__file__})  
    def debugInfo( pm ):
################################################################################
        global debugIndex
# Main
        traceback.format_stack()
################################################################################
        # frame,filename, num, func = inspect.getouterframes(
        #                                     inspect.currentframe())[1][:4]
        debugIndex += 1
        print("")
        print("id(pm)", id(pm) )
        print("debugIndex",debugIndex)
        for ll in traceback.format_stack()[:-1] :
            print( "   "+ll )
        print(pm)
        print("%s" %(pm.onGetInfo))
         print("%s %s" %(pm.pressureDropMaxTime, pm.pressureDropMax ))
        print("Enter");input()
}}


if __name__ == '__main__' :
{{code|lang=python|code=
     short = u"xh"
import traceback
     long = []
import sys
     opts,args=getopt.getopt( sys.argv[1:],short, long)
from testLib import exceptionProcess
    options = list()
               
    for opt,val in opts:
def myFunction2( a ):
         options.append( opt )
     myFunction( a )
      
 
     for opt,val in opts:
class MyClass :
        #if opt==u'-x' :
     def __init__(self,a):
         #    ...       
        self.a = a
        #if opt==u'--XXXXXX' :
     def do(self):
        #    ... 
        try :
        pass
            a = self.a / 0           
        except Exception as err :
            errMsg = exceptionProcess(err, sys.exc_info(),  
                                                    traceback.format_stack() )
            print(errMsg)
            exit(1)
          
def myFunction( a ):
     cl = MyClass(a)
     cl.do()
    print("End of myFunction")       
          
if __name__ == '__main__' :
    pass
    myFunction2( 3 )
}}


    if (len(args)==0) and (len(opts)==0) :
        options.append( u"-h" )


    if u'-h' in options  :
{{code||lang=python|code=
        help()
    else :
        # lauch requests ...
        pass
}}
}}googWay
 
=== Options en ligne de commande : getopt, help, CParams ===
{{parW|1=
generated by {{m|gen_main_options.py}} :
{{code|colNb=70|lang=python|code=
#!/usr/bin/python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
#***********************************************************
import inspect
"""\
import traceback
TODO
"""
import os
import sys
import getopt
#import string
#import re
#import time
#import shutil
################################################################################
################################################################################
# Version
def exceptionProcess(err, exeInfo, lastStack ):
################################################################################
APP_PATH, APP_NAME = os.path.split(__file__)
VERSION = u"0.1.0"
################################################################################
# Exceptions
################################################################################
class CAppException(Exception):
    """\
the exception class of the module
     """
     """
     pass
import sys
import traceback
import inspect
      
use :
errMsg = exceptionProcess(err, sys.exc_info(), traceback.format_stack() )
"""   
    frame,filename, num, func = inspect.getouterframes(
                                            inspect.currentframe())[1][:4]   
    last =  traceback.format_list(traceback.extract_tb(exeInfo[2]))[0]
    history = lastStack
    txt = ""
    for x in history[:-1] :
        txt += x
    txt += last
    txt += "catched p:%s\nline:%s func:%s\n" % (filename, num, func)   
    txt += "ERROR " + str(err)   
    return txt
################################################################################
################################################################################
# The process
}}
################################################################################
}}
def do_someThing(params):
 
    """\
==== Obtenir nom de fichier, numéro de ligne et nom de fonction ====
the main process
===== Cas simple mais non utile =====
    """
{{parW|1=
    print params.longParamVal
{{code|colNb=70|lang=python|code=
    raise CAppException("not good for us")
import inspect
################################################################################
 
# params
raisehead = "Error in %s:%s:%s\n" %inspect.getframeinfo(inspect.currentframe())[:3]
################################################################################
raise xmlBaseError("%sNo valid cardinality=%s for node named grammar in grammar" %(raisehead,node_nb))
class CParam(object):
}}
    """\
}}
parameters of the process
    """
    def __init__(self):
        """\
initialize all default values of parameters
        """
        self.errorMsg = ""
        self.shortParamBool = None
        self.shortParamVal = None
        self.longParamBool = None
        self.longParamVal = None


     def write_errorOnStdOutput(self):
===== Obtenir nom de fichier, numéro de ligne et nom de fonction de l'appelant  =====
         """\
{{parW|1=
print the parameter errors
{{code|colNb=70|lang=python|code=
        """
class xmlBaseError( Exception ) :
        for ms in self.errorMsg.split('\n'):
     def __init__(self, value):
            if ms.strip() != "":
         frame,filename, num, func = inspect.getouterframes(inspect.currentframe())[1][:4]
                print "ERROR: %s" % ms
        path, name = os.path.split(filename)
        exit(1)
        head="%s:%s:%s\n    " % ( name, num, func)
 
        self.value = head+value
     def checkParam(self):
     def __str__(self):
         """\
         return self.value
check parameters
}}
        """
}}
        ok = True
==== Un exemple simple pour tout exceptions en affichant la trace ====
        self.errorMsg = ""
{{parW|1=
        if self.shortParamBool != None:
{{code|colNb=70|lang=python|code=
            ok = True
#!/usr/bin/env python
            self.errorMsg += " ... \n"


        if self.shortParamVal != None:
try :
            ok = True
    raise ...
            self.errorMsg += " ... \n"


        if self.longParamBool != None:
except SomeException as err:
            ok = True
    errtrbk = traceback.format_exc()
            self.errorMsg += " ... \n"
    print "ERROR:\n%s\%s" %(str(err),errtrbk))


        if self.longParamVal != None:
    print u"MyException raised", e.__class__.__name__, e
            ok = True
else :
            self.errorMsg += " ... \n"
    print u"Unkown exeption :"
        if not ok:
}}
            self.write_errorOnStdOutput()
}}
        return ok
==== Un exemple avec importation ====
{{parW|1=
exception_test.py  :
{{code|colNb=70|lang=python|code=
class MyException( Exception ) :
    pass
}}
fonctions.py : 
{{code|colNb=70|lang=python|code=
from exception_test import MyException
 
def f() :
    raise MyException(u"test")
}}
raise.py :
{{code|colNb=70|lang=python|code=
#!/usr/bin/env python


################################################################################
from exception_test import MyException
# Help
from fonctions import f
################################################################################
def write_helpOnStdOutput():
    u"""\
print the help of the application
    """
    print u"""
Help on %(app)s:
-------------------
* %(app)s version %(version)s
    %(app)s -h


* Options:
try :
     -h:
     f()
      Print this help.
except MyException,e :
     -b
    print u"MyException raised", e.__class__.__name__, e
      ...
else :
    -v <val>
     print u"Unkown exeption"
      ...
}}
    --longBool
 
      ...
Résultats :
    --longVal <val>
{{code|colNb=70|lang=text|code=
      ...""" % ({u"app": APP_NAME, u"version": VERSION})
MyException raised MyException test
}}
}}
 
=== Options en ligne de commande ===
{{parW|1=
{{code|colNb=70|lang=python|code=
#!/usr/bin/python
# -*- coding: ISO8859-1 -*-
 
import os,sys, getopt


################################################################################
################################################################################
# Main
# Help
################################################################################
def help() :
    print u"""\
Help on %(app)s :
-------------------   
%(app)s -x -x AAA --XXXX --XXXX AAAA 
    -h :
        print this help
    """ % ({"app":__file__}) 
################################################################################
# Main
################################################################################
################################################################################
def executeMainProcess():
    """\
    execute main process
    """
    try:
        appParam = CParam()
        shortOption = u"hsv:"
        longOption = [u"longBool", u"longVal="]
        dohelp = False


        opts = getopt.getopt(sys.argv[1:], shortOption, longOption)[0]
if __name__ == '__main__' :
    short = u"xh"
    long = []
    opts,args=getopt.getopt( sys.argv[1:],short, long)
    options = list()
    for opt,val in opts:
        options.append( opt )
   
    for opt,val in opts:
        #if opt==u'-x' :
        #    ...       
        #if opt==u'--XXXXXX' :
        #    ... 
        pass


        for opt, val in opts:
    if (len(args)==0) and (len(opts)==0) :
        options.append( u"-h" )


            if opt == u'-h':
    if u'-h' in options  :
                dohelp = True
        help()
                write_helpOnStdOutput()
    else :
 
         # lauch requests ...
            if opt == u'-s':
         pass
                appParam.shortParamBool = True
 
            if opt == u'-v':
                appParam.shortParamVal = val
 
            if opt == u'--longBool':
                appParam.longParamBool = True
 
            if opt == u'--longVal':
                appParam.longParamVal = val
 
            else:
                pass
 
         appOk = appParam.checkParam()
        if (not dohelp) and appOk:
            do_someThing(appParam)
 
    except Exception as ex:
        info = sys.exc_info()
         raise CAppException("\nERRORS %s" % str(ex)), None, info[2]
 
if __name__ == u'__main__':
    executeMainProcess()
}}
}}
}}
}}googWay


=== execute - command - popen ===  
=== Options en ligne de commande : getopt, help, CParams ===
{{parW|1={{Alerte|texte=Utiliser plutôt [[#subprocess.Popen|subrocess]] (os.pepen est obsolète)}}
{{parW|1=
generated by {{m|gen_main_options.py}} :
{{code|colNb=70|lang=python|code=
{{code|colNb=70|lang=python|code=
def execute( command  ) :
#!/usr/bin/python
    print "cmd : ", command
    e = os.popen( command + " 2>&1" , "r" )
    out = e.read()   
    rc =  e.close()
    if rc == None :
        rc= 0
    std_out = out
    std_err="See Standard out"
    return rc, std_out, std_err
}}
En mode pas à pas; interception de la sortie standard en cours
{{code|colNb=70|lang=python|code=
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
import re
#***********************************************************
import subprocess
"""\
TODO
"""
import os
import sys
import sys
pat = re.compile("(\d\/\d)")
import getopt
def do(exe):
#import string
    sys.stdout.flush()
#import re
    try:
#import time
        p = subprocess.Popen(exe, stdout = subprocess.PIPE, stderr = \
#import shutil
                                                subprocess.STDOUT, shell = True)
################################################################################
    except Exception as err:
# Version
        print err
################################################################################
        sys.stdout.flush()
APP_PATH, APP_NAME = os.path.split(__file__)
     encore = True
VERSION = u"0.1.0"
     while(encore):
################################################################################
        retcode = p.poll()  # returns None while subprocess is running
# Exceptions
        sys.stdout.flush()
################################################################################
        line = p.stdout.readline()
class CAppException(Exception):
        val = pat.findall(line)
    """\
        if len(val) > 0:
the exception class of the module
            print val[0]
     """
        sys.stdout.flush()
     pass
        encore = retcode == None
################################################################################
     print "end"
# The process
if __name__ == '__main__':
################################################################################
     print "start"
def do_someThing(params):
     do("python cmd.py")
     """\
     print "end"
the main process
}}
     """
le programme {{mm|cmd.py}}
     print params.longParamVal
{{code|colNb=70|lang=python|code=
     raise CAppException("not good for us")
#!/usr/bin/python
################################################################################
# -*- coding: UTF-8 -*-
# params
import sys
################################################################################
import time
class CParam(object):
nb = 10
    """\
for x in range(nb):
parameters of the process
    print "toto %d/%d" % (x, nb)
    """
    sys.stdout.flush()
    def __init__(self):
    time.sleep(1.0)
        """\
}} 
initialize all default values of parameters
}}
        """
        self.errorMsg = ""
        self.shortParamBool = None
        self.shortParamVal = None
        self.longParamBool = None
        self.longParamVal = None


=== execute - command - subprocess - popen ===
    def write_errorOnStdOutput(self):
{{parW|1={{id|subprocess.Popen}}
        """\
{{code|colNb=70|lang=python|code=
print the parameter errors
def executeInShell( shellcmd  ) :
        """
    process = subprocess.Popen( shellcmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )   
        for ms in self.errorMsg.split('\n'):
    stdoutdata, stderrdata = process.communicate()       
            if ms.strip() != "":
    return process.returncode, stdoutdata, stderrdata
                print "ERROR: %s" % ms
}}
        exit(1)
 
    def checkParam(self):
        """\
check parameters
        """
        ok = True
        self.errorMsg = ""
        if self.shortParamBool != None:
            ok = True
            self.errorMsg += " ... \n"


Exécution en mode synchrone avec capture progressive de
        if self.shortParamVal != None:
{{code|colNb=70|lang=python|code=
            ok = True
#!/usr/bin/python
            self.errorMsg += " ... \n"
# -*- coding: UTF-8 -*-
import re
import subprocess
import sys
# patTelemacIteration = re.compile("(\d+\/\d+)")
patTelemacIteration = re.compile("ITERATION +(\d+) +TEMPS")


def executeExternalShellCommand(exe):
        if self.longParamBool != None:
    sys.stdout.flush()
            ok = True
    try:
            self.errorMsg += " ... \n"
        p = subprocess.Popen(exe, stdout = subprocess.PIPE, stderr = \
 
                                                subprocess.STDOUT, shell = True)
        if self.longParamVal != None:
    except Exception as err:
            ok = True
        print err
            self.errorMsg += " ... \n"
        sys.stdout.flush()
         if not ok:
    encore = True
            self.write_errorOnStdOutput()
    while(encore):
         return ok
        retcode = p.poll()  # returns None while subprocess is running
 
        sys.stdout.flush()
################################################################################
         line = p.stdout.readline()
# Help
         print line
################################################################################
        val = patTelemacIteration.findall(line)
def write_helpOnStdOutput():
        print val
     u"""\
        if len(val) > 0:
print the help of the application
            print int(val[0])
     """
        sys.stdout.flush()
     print u"""
        encore = retcode == None
Help on %(app)s:
     print "end"
-------------------
if __name__ == '__main__':
* %(app)s version %(version)s
     print "start"
     %(app)s -h
    executeExternalShellCommand("cd ...; python cmd.py")
     print "end"
}}
{{code|colNb=70|lang=python|code=
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import time
nb = 10
for x in range(nb):
    print " ITERATION      %d  TEMPS : 15 MN  0.0000 S  (     900.0000 S) IT\
ERATION      200  TEMPS" % (x)
     sys.stdout.flush()
    time.sleep(1.0)
}}
}}
==== Get directly the output ====
{{parW|1=
{{code|colNb=70|lang=python|code=
result = subprocess.check_output("gsettings get org.gnome.desktop.background picture-uri", shell=True)
}}
}}
=== isLanched ===
{{parW|1=<span id="subprocess.Popen"></span>
{{code|colNb=70|lang=python|code=


def isLanched( procName ):
* Options:
     import psutil, string
     -h:
    pid = os.getpid()
      Print this help.
     patText = re.escape(procName)
     -b
     pat = re.compile( ".*%s.*" % patText )
      ...
     ok = False
     -v <val>
    for proc in psutil.process_iter():
      ...
        if pid != proc.pid :
     --longBool
            if pat.match( string.join(proc.cmdline()," ") )  :
      ...
                ok=True
    --longVal <val>
    return ok
      ...""" % ({u"app": APP_NAME, u"version": VERSION})
}}
}}
=== Ajouter des répertoire dans le path python en dynamique ===
{{parW|1=
{{code|colNb=70|lang=python|code=
import sys
sys.path.append("/home/me/mypy")  
}}
}}


== La commande print ==
################################################################################
=== Afficher sur la sortie d'erreurs (stderr) ===
# Main
{{parW|1=
################################################################################
{{code|lang=python|code=
def executeMainProcess():
print >> sys.stderr, "Error ..."
    """\
}}
    execute main process
    """
    try:
        appParam = CParam()
        shortOption = u"hsv:"
        longOption = [u"longBool", u"longVal="]
        dohelp = False


en Python 3 :
        opts = getopt.getopt(sys.argv[1:], shortOption, longOption)[0]
{{code|lang=python|code=
print(5, "toto", file=sys.stderr)
}}


Sa propre fonction:
        for opt, val in opts:
{{code|lang=python|code=
def conErrOut(*args):
    print(*args, file=sys.stderr, **kwargs)
}}
}}


== Design pattern, POO, Algorithmes ==
            if opt == u'-h':
=== POO Programmation orientée objet ===
                dohelp = True
==== class attribute - instance attribute ====
                write_helpOnStdOutput()
{{parW|1=
{{code|lang=python|code=
class CObj(object):
  classAttr = 0
  def __init__(self, name, instance_attr):
    self.name = name
    self.objAttr = instance_attr
  def __str__(self):
    return "%s %s %s %s" %(self.name, self.classAttr, self.objAttr, self.__dict__)


if __name__ == '__main__':
            if opt == u'-s':
   
                appParam.shortParamBool = True
    obj1 = CObj("A", 1)
    obj2 = CObj("B", 2)


   
            if opt == u'-v':
    print (CObj.classAttr)
                appParam.shortParamVal = val
    print (obj1.classAttr)
 
    print (obj2.classAttr)
            if opt == u'--longBool':
    print( obj1 )
                appParam.longParamBool = True
    print( obj2 )
 
    print()
            if opt == u'--longVal':
   
                appParam.longParamVal = val
    CObj.classAttr += 1
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()


    obj1.classAttr += 1    # ATTENTION PIEGE
            else:
    print (CObj.classAttr)
                pass
    print (obj1.classAttr)
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()


    obj2.classAttr += 1    # ATTENTION PIEGE
        appOk = appParam.checkParam()
    print (CObj.classAttr)
        if (not dohelp) and appOk:
    print (obj1.classAttr)
            do_someThing(appParam)
    print (obj2.classAttr)  
 
    print( obj1 )
     except Exception as ex:
    print( obj2 )
        info = sys.exc_info()
     print()
        raise CAppException("\nERRORS %s" % str(ex)), None, info[2]
    CObj.classAttr += 1
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()


     print (CObj.objAttr)   # ERROR
if __name__ == u'__main__':
     executeMainProcess()
}}
}}
}}
{{code|lang=text|code=
0
0
0
A 0 1 {'objAttr': 1, 'name': 'A'}
B 0 2 {'objAttr': 2, 'name': 'B'}


1
=== execute - command - popen ===
1
{{parW|1={{Alerte|texte=Utiliser plutôt [[#subprocess.Popen|subrocess]] (os.pepen est obsolète)}}
1
{{code|colNb=70|lang=python|code=
A 1 1 {'objAttr': 1, 'name': 'A'}
def execute( command  ) :
B 1 2 {'objAttr': 2, 'name': 'B'}
    print "cmd : ", command
 
    e = os.popen( command + " 2>&1" , "r" )
1
    out = e.read()   
2
    rc =  e.close()
1
    if rc == None :
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
        rc= 0
B 1 2 {'objAttr': 2, 'name': 'B'}
    std_out = out
 
    std_err="See Standard out"
1
    return rc, std_out, std_err
2
2
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 2 2 {'objAttr': 2, 'name': 'B', 'classAttr': 2}
 
2
2
2
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 2 2 {'objAttr': 2, 'name': 'B', 'classAttr': 2}
 
Traceback (most recent call last):
  File "testP.py", line 55, in <module>
    print (CObj.objAttr)
AttributeError: type object 'CObj' has no attribute 'objAttr'
}}
}}
En mode pas à pas; interception de la sortie standard en cours
{{code|colNb=70|lang=python|code=
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import subprocess
import sys
pat = re.compile("(\d\/\d)")
def do(exe):
    sys.stdout.flush()
    try:
        p = subprocess.Popen(exe, stdout = subprocess.PIPE, stderr = \
                                                subprocess.STDOUT, shell = True)
    except Exception as err:
        print err
        sys.stdout.flush()
    encore = True
    while(encore):
        retcode = p.poll()  # returns None while subprocess is running
        sys.stdout.flush()
        line = p.stdout.readline()
        val = pat.findall(line)
        if len(val) > 0:
            print val[0]
        sys.stdout.flush()
        encore = retcode == None
    print "end"
if __name__ == '__main__':
    print "start"
    do("python cmd.py")
    print "end"
}}
le programme {{mm|cmd.py}}
{{code|colNb=70|lang=python|code=
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import time
nb = 10
for x in range(nb):
    print "toto %d/%d" % (x, nb)
    sys.stdout.flush()
    time.sleep(1.0)
}} 
}}
}}


=== Sérialisation ===
=== execute - command - subprocess - popen ===
==== pickle ====
{{parW|1={{id|subprocess.Popen}}
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|lang=python|code=
def executeInShell( shellcmd ) :
################################################################################
     process = subprocess.Popen( shellcmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )  
import pickle
     stdoutdata, stderrdata = process.communicate()      
def objToFile( obj, fileName ):
     return process.returncode, stdoutdata, stderrdata
     with open(fileName, 'wb') as handle:
        pickle.dump( obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
#-------------------------------------------------------------------------------
def objFormFile(  fileName  ):
    with open(fileName, 'rb') as handle:
        obj = pickle.load(handle)
    return obj
################################################################################
}}
}}
 
=== POO ===
==== CDictList ====
{{parW|1=
<source lang="python">
class CDictList :
    def __init__( self, name ) :
        self.name = name
        self.d = dict()
        self.l = list()
       
     def add( self, obj, name  ) :
        if name in self.d :
            raise Exception(
                    "object named '%s' is already in CDictList named '%s'"
                    % ( name, self.name ) )
        self.d[ name ] = obj
        self.l.append( obj )  
</source>
}}
 
=== Génération de code ===
==== Générer une fonction ====
{{parW|1=
<source lang="python">
correctionCoefficient=[ (-5000,-5000), (-4000,-4800), (-1000,-3000), (-50,-1000), (0,0), (400, 5), (500, 10), (1000, 1000),(5000, 5000) ]
def createCorrectionFunction(  ) :
     fileName="func.py"
    txt = "#!/usr/bin/python\n"
    txt += "# -*- coding: UTF-8 -*-\n"   
    txt += "def hcorection( val ) :\n"
    txt += "    nval=val\n"
   
    a=correctionCoefficient[0]
    for b in correctionCoefficient[1:] :   
        txt += "    if (val > %d) and (val <=%d) :\n" %( a[0], b[0] )
        txt += "        nval =  ( val- %f )*%f +  %f\n" %( a[0], float(b[1]-a[1])/(b[0]-a[0])  ,a[1] )
        a=b
    txt += "    return nval\n"
    tofile( fileName, txt )
</source>
Ce qui donne la fonction suivante :
{{fig|Exemple|create_function_ex01.png||512px}}
}}
}}


=== Design pattern ===
Exécution en mode synchrone avec capture progressive de
==== Singleton ====
{{code|colNb=70|lang=python|code=
{{parW|1=
#!/usr/bin/python
Voici un petit code écrit en python qui explique comment écrire un singleton en langage python. Notez bien que dans la méthode {{m|__init__}} il faut faire quelques vérifications notamment avec les listes.
# -*- coding: UTF-8 -*-
 
import re
<source lang="python">
import subprocess
class CSingleton( object ):
import sys
    class_instance = None
# patTelemacIteration = re.compile("(\d+\/\d+)")
    def __init__( self, a ):
patTelemacIteration = re.compile("ITERATION +(\d+) +TEMPS")
        print "CSingleton init"
        self.vitesse = a
        if not hasattr( self, "alist") :
            self.alist = list()
   
    def __new__( typ, *args, **kwargs ):
        print "CSingleton new", typ.class_instance       
        if typ.class_instance == None :
            obj = object.__new__( typ, *args, **kwargs)
            typ.class_instance = obj
        else :
            obj = typ.class_instance       
        return obj


    def addObject(self, obj):
def executeExternalShellCommand(exe):
        self.alist.append( obj )
    sys.stdout.flush()
 
    try:
if __name__ == '__main__' :
        p = subprocess.Popen(exe, stdout = subprocess.PIPE, stderr = \
    a = CSingleton( 1 )
                                                subprocess.STDOUT, shell = True)
     a.addObject( "Lundi" )
     except Exception as err:
     print "a.vitesse=",a.vitesse
        print err
     print "a.alist=",a.alist
        sys.stdout.flush()
 
     encore = True
    b = CSingleton( 2 )
     while(encore):
    b.addObject( "Mardi" )
        retcode = p.poll()  # returns None while subprocess is running
    print "b.vitesse=",b.vitesse
        sys.stdout.flush()
    print "b.alist=",b.alist
        line = p.stdout.readline()
 
        print line
    c = CSingleton( 3 )
        val = patTelemacIteration.findall(line)
    c.addObject( "Mercredi" )
        print val
    print "c.vitesse=",c.vitesse
        if len(val) > 0:
     print "c.alist=",c.alist
            print int(val[0])
 
        sys.stdout.flush()
     print "a.vitesse=",a.vitesse
        encore = retcode == None
     print "a.alist=",a.alist
     print "end"
     print "b.vitesse=",b.vitesse
if __name__ == '__main__':
    print "b.alist=",b.alist
     print "start"
    print "c.vitesse=",c.vitesse
     executeExternalShellCommand("cd ...; python cmd.py")
     print "c.alist=",c.alist
     print "end"
    print "id(a)=",id(a)
}}
     print "id(b)=",id(b)
{{code|colNb=70|lang=python|code=
    print "id(c)=",id(c)
#!/usr/bin/python
</source>
# -*- coding: UTF-8 -*-
import sys
import time
nb = 10
for x in range(nb):
     print " ITERATION      %d  TEMPS : 15 MN  0.0000 S  (      900.0000 S) IT\
ERATION      200  TEMPS" % (x)
    sys.stdout.flush()
     time.sleep(1.0)
}}
}}
==== Get directly the output ====
{{parW|1=
{{code|colNb=70|lang=python|code=
result = subprocess.check_output("gsettings get org.gnome.desktop.background picture-uri", shell=True)
}}
}}
=== isLanched ===
{{parW|1=<span id="subprocess.Popen"></span>
{{code|colNb=70|lang=python|code=


Ce qui donne :
def isLanched( procName ):
<source lang="bash">
    import psutil, string
python singleton.py
    pid = os.getpid()
CSingleton new None
    patText = re.escape(procName)
CSingleton init
    pat = re.compile( ".*%s.*" % patText )
a.vitesse= 1
    ok = False
a.alist= ['Lundi']
    for proc in psutil.process_iter():
CSingleton new <__main__.CSingleton object at 0xb7cf8ecc>
        if pid != proc.pid :
CSingleton init
            if pat.match( string.join(proc.cmdline()," ") )  :
b.vitesse= 2
                ok=True
b.alist= ['Lundi', 'Mardi']
    return ok
CSingleton new <__main__.CSingleton object at 0xb7cf8ecc>
}}
CSingleton init
}}
c.vitesse= 3
=== Ajouter des répertoire dans le path python en dynamique ===
c.alist= ['Lundi', 'Mardi', 'Mercredi']
{{parW|1=
a.vitesse= 3
{{code|colNb=70|lang=python|code=
a.alist= ['Lundi', 'Mardi', 'Mercredi']
import sys
b.vitesse= 3
sys.path.append("/home/me/mypy")  
b.alist= ['Lundi', 'Mardi', 'Mercredi']
}}
c.vitesse= 3
c.alist= ['Lundi', 'Mardi', 'Mercredi']
id(a)= 3083833036
id(b)= 3083833036
id(c)= 3083833036
</source>
}}
}}


=== Algorithmes ===
== La commande print ==
==== resgression linéaire en 3 dimensions pour obtenir un plan optimum pour une nuage de points ====
=== Afficher sur la sortie d'erreurs (stderr) ===
{{parW|1=
{{parW|1=
{{codeTr|lang=python|code=
{{code|lang=python|code=
import numpy as np
print >> sys.stderr, "Error ..."
################################################################################
}}
nbpts = 10 # nombre de points par axe
 
a = 5. # paramètres du plan
en Python 3 :
b = 3.
{{code|lang=python|code=
c = 2.
print(5, "toto", file=sys.stderr)
d = 10.
}}
sigma = 0.1 # écart type
################################################################################
def planXyz(x, y, z,  A):
    return A[0]*x + A[1]*y + A[2]*z + A[3]
################################################################################
def lienarRegressionXyz(X,Y,Z):
    points = np.hstack(
            (
                X, Y, Z, np.ones_like(X)
            )
        )
    resultat = np.linalg.lstsq(points, T)
    aopt, bopt, copt, dopt = resultat[0]
    erreur = resultat[1][0]/(nbpts*nbpts)
    return  aopt, bopt, copt, dopt,erreur
################################################################################
x = np.linspace(0, 1, nbpts)
y = np.linspace(0, 1, nbpts)
z = np.linspace(0, 1, nbpts)


grilleX, grilleY, grilleZ = np.meshgrid(x, y, z)
Sa propre fonction:
################################################################################
{{code|lang=python|code=
X = grilleX.flatten().reshape(nbpts*nbpts*nbpts, 1)
def conErrOut(*args):
Y = grilleY.flatten().reshape(nbpts*nbpts*nbpts, 1)
    print(*args, file=sys.stderr, **kwargs)
Z = grilleZ.flatten().reshape(nbpts*nbpts*nbpts, 1)
T = planXyz(X, Y, Z,  (a, b, c, d)) + sigma*np.random.randn(nbpts*nbpts*nbpts,
                                                                            1)
################################################################################
a,b,c,d,e = lienarRegressionXyz(X,Y,Z)
print(
    "a=%f b=%f c=%f d=%f χ²=%f" %( a,b,c,d,e ))
}}
}}
}}
}}
==== Filtre passe bas - exemple ====
 
== Design pattern, POO, Algorithmes ==
=== POO Programmation orientée objet ===
==== class attribute - instance attribute ====
{{parW|1=
{{parW|1=
{{codeTr|lang=python|code=
{{code|lang=python|code=
from scipy import signal
class CObj(object):
import matplotlib.pyplot as plt
  classAttr = 0
import numpy as np
  def __init__(self, name, instance_attr):
    self.name = name
    self.objAttr = instance_attr
  def __str__(self):
    return "%s %s %s %s" %(self.name, self.classAttr, self.objAttr, self.__dict__)


t = np.linspace(0, 1, 1000, False) # 1 second
if __name__ == '__main__':
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5
   
    obj1 = CObj("A", 1)
    obj2 = CObj("B", 2)


class lpFilter:
    def __init__(self, fc, fe):
        self.fc = fc
        self.fe = fe
        self.τ = 1/fc
        self.Te = 1 / fe
        self.α = self.τ / (self.τ + self.Te)
      
      
     def filter(self, sig):
     print (CObj.classAttr)
        yf_0 = sig[0]
    print (obj1.classAttr)
        yf_1 = yf_0
    print (obj2.classAttr)
        yf = list()
    print( obj1 )
        for y in sig:
    print( obj2 )
            yf_0 = self.α * yf_1 + (1-self.α)* y
    print()
            yf_1 = yf_0
   
            yf.append(yf_0)
    CObj.classAttr += 1
        return yf
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()


flp = lpFilter( 15, 1000 )
    obj1.classAttr += 1    # ATTENTION PIEGE
yf = flp.filter( sig )
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()


plt.plot(t, yf, label='yf')
    obj2.classAttr += 1    # ATTENTION PIEGE
plt.plot(t, sig, label='sig')
    print (CObj.classAttr)
plt.legend()
    print (obj1.classAttr)
plt.show()
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()
    CObj.classAttr += 1
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)   
    print( obj1 )
    print( obj2 )
    print()
 
    print (CObj.objAttr)   # ERROR
}}
}}
{{fig|Exemple filttre linéaire|filtrePasseBasLineaireExample.png||512px}}
{{code|lang=text|code=
0
0
0
A 0 1 {'objAttr': 1, 'name': 'A'}
B 0 2 {'objAttr': 2, 'name': 'B'}


Utilisation de ellip :
1
{{codeTr|lang=python|code=
1
from scipy import signal
1
import matplotlib.pyplot as plt
A 1 1 {'objAttr': 1, 'name': 'A'}
import numpy as np
B 1 2 {'objAttr': 2, 'name': 'B'}


t = np.linspace(0, 1, 1000, False)  # 1 second
1
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5
2
1
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 1 2 {'objAttr': 2, 'name': 'B'}
 
1
2
2
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 2 2 {'objAttr': 2, 'name': 'B', 'classAttr': 2}


sos = signal.ellip(8, 1, 100, 5, 'lowpass', fs=1000, output='sos')
2
filtered = signal.sosfilt(sos, sig)
2
2
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 2 2 {'objAttr': 2, 'name': 'B', 'classAttr': 2}


plt.plot(t, filtered)
Traceback (most recent call last):
plt.plot(t, sig)
  File "testP.py", line 55, in <module>
plt.show()
    print (CObj.objAttr)
AttributeError: type object 'CObj' has no attribute 'objAttr'
}}
}}
}}
{{fig|ellip exemple|filtrePasseBasEllipExample.png||512px}}


Diagramme des fréquences:
=== Sérialisation ===
{{codeTr|lang=python|code=
==== pickle ====
from scipy import signal
{{parW|1=
import matplotlib.pyplot as plt
{{code|lang=python|code=
import numpy as np
################################################################################
 
import pickle
b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True)
def objToFile( obj, fileName  ):
w, h = signal.freqs(b, a)
    with open(fileName, 'wb') as handle:
        pickle.dump( obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
plt.semilogx(w, 20 * np.log10(abs(h)))
#-------------------------------------------------------------------------------
def objFormFile( fileName  ):
plt.title('Elliptic filter frequency response (rp=5, rs=40)')
    with open(fileName, 'rb') as handle:
plt.xlabel('Frequency [radians / second]')
        obj = pickle.load(handle)
plt.ylabel('Amplitude [dB]')
    return obj
plt.margins(0, 0.1)
################################################################################
plt.grid(which='both', axis='both')
plt.axvline(100, color='green') # cutoff frequency
plt.axhline(-40, color='green') # rs
plt.axhline(-5, color='green') # rp
plt.show()
}}
}}
{{fig|Diagramme des fréquences - ellip exemple|filtrePasseBasDiagrammeDesFrequences.png||512px}}
}}
}}


==== Filtre passe haut - exemple ====
=== POO ===
==== CDictList ====
{{parW|1=
{{parW|1=
 
<source lang="python">
Utilisation de ellip :
class CDictList :
{{codeTr|lang=python|code=
    def __init__( self, name ) :
from scipy import signal
        self.name = name
import matplotlib.pyplot as plt
        self.d = dict()
import numpy as np
        self.l = list()
 
       
t = np.linspace(0, 1, 1000, False) # 1 second
    def add( self, obj, name ) :
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5
        if name in self.d :
 
            raise Exception(  
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
                    "object named '%s' is already in CDictList named '%s'"
ax1.set_title('10 Hz and 20 Hz sinusoids')
                    % ( name, self.name ) )
ax1.axis([0, 1, -2, 3.5])
        self.d[ name ] = obj
   
        self.l.append( obj )  
ax2.set_title('After 17 Hz high-pass filter')
</source>
ax2.axis([0, 1, -2, 2])
ax2.set_xlabel('Time [seconds]')
sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos')
filtered = signal.sosfilt(sos, sig)
ax1.plot(t, sig)
ax2.plot(t, filtered)
plt.tight_layout()
plt.show()
}}
}}
}}


==== Fonction rapide d'interpolation linéaire - Functor ====
=== Génération de code ===
{{parW|1=[[Algorithmique#fastLinearInterpolationFunctionAsFonctor|algorithmique]]
==== Générer une fonction ====
{{parW|1=
<source lang="python">
correctionCoefficient=[ (-5000,-5000), (-4000,-4800), (-1000,-3000), (-50,-1000), (0,0), (400, 5), (500, 10), (1000, 1000),(5000, 5000) ]
def createCorrectionFunction(  ) :
    fileName="func.py"
    txt = "#!/usr/bin/python\n"
    txt += "# -*- coding: UTF-8 -*-\n"   
    txt += "def hcorection( val ) :\n"
    txt += "    nval=val\n"
   
    a=correctionCoefficient[0]
    for b in correctionCoefficient[1:] :   
        txt += "    if (val > %d) and (val <=%d) :\n" %( a[0], b[0] )
        txt += "        nval =  ( val- %f )*%f +  %f\n" %( a[0], float(b[1]-a[1])/(b[0]-a[0])  ,a[1] )
        a=b
    txt += "    return nval\n"
    tofile( fileName, txt )
</source>
Ce qui donne la fonction suivante :
{{fig|Exemple|create_function_ex01.png||512px}}
}}
}}


==== Adapter Rectangle Dans Zone ====
=== Design pattern ===
{{parW|1={{id|AdapterRectangleDansZone}}
==== Singleton ====
* [[Pascal#AdapterRectangleDansZone|Version en Pascal]]
{{parW|1=
{{codeTr|lang=python|code=
Voici un petit code écrit en python qui explique comment écrire un singleton en langage python. Notez bien que dans la méthode {{m|__init__}} il faut faire quelques vérifications notamment avec les listes.
def AdapterRectangleDansZone( zone_x,zone_y,zone_l,zone_h, rect_l, rect_h, rlimte ) :
 
  if (zone_h > 0 ) and (rect_h>0) :
<source lang="python">
      r1 = zone_l / zone_h
class CSingleton( object ):
      r2 = rect_l / rect_h
    class_instance = None
      #print r1,r2
    def __init__( self, a ):
      if r1 >= r2 :
        print "CSingleton init"
          if rlimte > 0 :
        self.vitesse = a
              r = zone_h / rect_h
        if not hasattr( self, "alist") :
              if r > rlimte :
            self.alist = list()
                  r = rlimte
   
                  hh = round( rect_h*r )
    def __new__( typ, *args, **kwargs ):
                  ll = round( rect_l*r )
        print "CSingleton new", typ.class_instance       
                  newrect_y = zone_y  +( zone_h-hh ) / 2
        if typ.class_instance == None :
                  newrect_h = hh
            obj = object.__new__( typ, *args, **kwargs)
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
            typ.class_instance = obj
                  newrect_l = ll
        else :
              else :
            obj = typ.class_instance       
                  hh = zone_h
        return obj
                  ll = round( zone_h*r2 )
 
                  newrect_y = zone_y
    def addObject(self, obj):
                  newrect_h = hh
        self.alist.append( obj )
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
 
                  newrect_l = ll
if __name__ == '__main__' :
          else :
    a = CSingleton( 1 )
            hh = zone_h
    a.addObject( "Lundi" )
            ll = round( zone_h*r2 )
    print "a.vitesse=",a.vitesse
            newrect_y = zone_y
    print "a.alist=",a.alist
            newrect_h = hh
 
            newrect_x = zone_x  + (zone_l-ll) / 2
    b = CSingleton( 2 )
            newrect_l = ll
    b.addObject( "Mardi" )
      else :
    print "b.vitesse=",b.vitesse
          if rlimte > 0 :
    print "b.alist=",b.alist
              r = zone_l / rect_l
 
              if r > rlimte :
    c = CSingleton( 3 )
                  r = rlimte
    c.addObject( "Mercredi" )
                  hh = round( rect_h*r )
    print "c.vitesse=",c.vitesse
                  ll = round( rect_l*r )
    print "c.alist=",c.alist
                  newrect_y = zone_y  +( zone_h-hh ) / 2
 
                  newrect_h = hh
    print "a.vitesse=",a.vitesse
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
    print "a.alist=",a.alist
                  newrect_l = ll
    print "b.vitesse=",b.vitesse
              else :
    print "b.alist=",b.alist
                  ll = zone_l
    print "c.vitesse=",c.vitesse
                  hh = round( ll/r2 )
    print "c.alist=",c.alist
                  newrect_x = zone_x
    print "id(a)=",id(a)
                  newrect_l = ll
    print "id(b)=",id(b)
                  newrect_y = zone_y  + ( zone_h-hh ) / 2
    print "id(c)=",id(c)
                  newrect_h = hh
</source>
          else :
              ll = zone_l
              hh = round( ll/r2 )
              newrect_x = zone_x
              newrect_l = ll
              newrect_y = zone_y  + ( zone_h-hh ) / 2
              newrect_h = hh
  else :
      newrect_x = zone_x
      newrect_l = 0
      newrect_y = zone_y
      newrect_h = 0


  return newrect_x,newrect_y,newrect_l,newrect_h
Ce qui donne :
}}
<source lang="bash">
}}
python singleton.py
 
CSingleton new None
==== Fonction de comparaison pour les tri : sort ====
CSingleton init
===== Avec python 2 =====
a.vitesse= 1
a.alist= ['Lundi']
CSingleton new <__main__.CSingleton object at 0xb7cf8ecc>
CSingleton init
b.vitesse= 2
b.alist= ['Lundi', 'Mardi']
CSingleton new <__main__.CSingleton object at 0xb7cf8ecc>
CSingleton init
c.vitesse= 3
c.alist= ['Lundi', 'Mardi', 'Mercredi']
a.vitesse= 3
a.alist= ['Lundi', 'Mardi', 'Mercredi']
b.vitesse= 3
b.alist= ['Lundi', 'Mardi', 'Mercredi']
c.vitesse= 3
c.alist= ['Lundi', 'Mardi', 'Mercredi']
id(a)= 3083833036
id(b)= 3083833036
id(c)= 3083833036
</source>
}}
 
=== Algorithmes ===
==== resgression linéaire en 3 dimensions pour obtenir un plan optimum pour une nuage de points ====
{{parW|1=
{{parW|1=
La comparaison suivante range dans l'ordre des valeurs croissantes:
{{codeTr|lang=python|code=
{{code|lang=python|code=
import numpy as np
def myCmp(pntA, pntB):
################################################################################
     rc = 0
nbpts = 10 # nombre de points par axe
     if pntA < pntB:
a = 5. # paramètres du plan
         rc = -1
b = 3.
     elif pntA > pntB:
c = 2.
        rc = 1
d = 10.
     return rc
sigma = 0.1 # écart type
################################################################################
def planXyz(x, y, z, A):
     return A[0]*x + A[1]*y + A[2]*z + A[3]
################################################################################
def lienarRegressionXyz(X,Y,Z):
     points = np.hstack(
            (
                X, Y, Z, np.ones_like(X)
            )
         )
    resultat = np.linalg.lstsq(points, T)
     aopt, bopt, copt, dopt = resultat[0]
    erreur = resultat[1][0]/(nbpts*nbpts)
     return aopt, bopt, copt, dopt,erreur
################################################################################
x = np.linspace(0, 1, nbpts)
y = np.linspace(0, 1, nbpts)
z = np.linspace(0, 1, nbpts)


vals = [ 1, 5, 6, 0, -15 ]
grilleX, grilleY, grilleZ = np.meshgrid(x, y, z)
vals.sort(myCmp)
################################################################################
print vals
X = grilleX.flatten().reshape(nbpts*nbpts*nbpts, 1)
}}
Y = grilleY.flatten().reshape(nbpts*nbpts*nbpts, 1)
ce qui donne :
Z = grilleZ.flatten().reshape(nbpts*nbpts*nbpts, 1)
{{code|lang=python|code=
T = planXyz(X, Y, Z, (a, b, c, d)) + sigma*np.random.randn(nbpts*nbpts*nbpts,
[-15, 0, 1, 5, 6]
                                                                            1)
################################################################################
a,b,c,d,e = lienarRegressionXyz(X,Y,Z)
print(
    "a=%f b=%f c=%f d=%f χ²=%f" %( a,b,c,d,e ))
}}
}}
}}
}}
===== Avec Python 3 =====
==== Filtre passe bas - exemple ====
{{parW|1=
{{parW|1=
Le tri se fait dans l'ordre croissant !
{{codeTr|lang=python|code=
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np


Pour les tuples ou listes imbriqués, tri sur l'indice n
t = np.linspace(0, 1, 1000, False)  # 1 second
{{code|lang=python|code=
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5
myList = sorted(myList, key = lambda els: els[n])
}}


{{code|lang=python|code=
class lpFilter:
sprocketTeethPointList1.sort( key = lambda pnt: pnt.angle)
    def __init__(self, fc, fe):
}}
        self.fc = fc
ou
        self.fe = fe
{{code|lang=python|code=
        self.τ = 1/fc
sprocketTeethPointList1 = sorted(sprocketTeethPointList1,
        self.Te = 1 / fe
                            key = lambda pnt: pnt.angle)
        self.α = self.τ / (self.τ + self.Te)
 
   
}}
    def filter(self, sig):
ou
        yf_0 = sig[0]
{{code|lang=python|code=
        yf_1 = yf_0
def angledPointKey(key ):
        yf = list()
    return key.angle
        for y in sig:
            yf_0 = self.α * yf_1 + (1-self.α)* y
            yf_1 = yf_0
            yf.append(yf_0)
        return yf


sprocketTeethPointList1 = sorted(sprocketTeethPointList1, key = angledPointKey )
flp = lpFilter( 15, 1000 )
}}
yf = flp.filter( sig )


ou
plt.plot(t, yf, label='yf')
{{code|lang=python|code=
plt.plot(t, sig, label='sig')
def cmpIntAPy3( aa ):
plt.legend()
    a = aa.serviceDate
plt.show()
    if a == None :
        a = aa.prototypeDate   
    return a
 
self.intAs = sorted(self.intAs, key = cmpIntAPy3 )
}}
}}
{{fig|Exemple filttre linéaire|filtrePasseBasLineaireExample.png||512px}}


}}
Utilisation de ellip :
{{codeTr|lang=python|code=
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np


===== Avec Python 3 à la manière de Python 2=====
t = np.linspace(0, 1, 1000, False) # 1 second
{{parW|1=
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5
{{code|lang=python|code=
def angledPointClass( myCmpFunc ) :
    class K :
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return myCmpFunc(self.obj, other.obj) < 0
        def __gt__(self, other):
            return myCmpFunc(self.obj, other.obj) > 0
        def __eq__(self, other):
            return myCmpFunc(self.obj, other.obj) == 0
        def __le__(self, other):
            return myCmpFunc(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return myCmpFunc(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return myCmpFunc(self.obj, other.obj) != 0
    return K       


def angledPointCmp(pntA, pntB):
sos = signal.ellip(8, 1, 100, 5, 'lowpass', fs=1000, output='sos')
    rc = 0
filtered = signal.sosfilt(sos, sig)
    pntA = pntA.angle
    pntB = pntB.angle
    if pntA < pntB:
        rc = -1
    elif pntA > pntB:
        rc = 1
    return rc 


sprocketTeethPointList1.sort( key=angledPointClass(angledPointCmp) )
plt.plot(t, filtered)
}}
plt.plot(t, sig)
plt.show()
}}
}}
{{fig|ellip exemple|filtrePasseBasEllipExample.png||512px}}


== Clavier, Input device ==
Diagramme des fréquences:
=== get_char ===
{{codeTr|lang=python|code=
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
 
b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True)
w, h = signal.freqs(b, a)
plt.semilogx(w, 20 * np.log10(abs(h)))
plt.title('Elliptic filter frequency response (rp=5, rs=40)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Amplitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(100, color='green') # cutoff frequency
plt.axhline(-40, color='green') # rs
plt.axhline(-5, color='green') # rp
plt.show()
}}
{{fig|Diagramme des fréquences - ellip exemple|filtrePasseBasDiagrammeDesFrequences.png||512px}}
}}
 
==== Filtre passe haut - exemple ====
{{parW|1=
{{parW|1=
voir {{m|curses.window.getch()}} pour une implémentation sous linux.
 
<source lang="python">
Utilisation de ellip :
if os.name=="nt" :
{{codeTr|lang=python|code=
    import msvcrt
from scipy import signal
    def get_char() :
import matplotlib.pyplot as plt
        if msvcrt.kbhit() :
import numpy as np
            return msvcrt.getch()
 
        else :
t = np.linspace(0, 1, 1000, False) # 1 second
            return None
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5
else :
 
    print "Error : No get_char()"
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
    exit(1)
ax1.set_title('10 Hz and 20 Hz sinusoids')
</source>
ax1.axis([0, 1, -2, 3.5])
ax2.set_title('After 17 Hz high-pass filter')
ax2.axis([0, 1, -2, 2])
ax2.set_xlabel('Time [seconds]')
sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos')
filtered = signal.sosfilt(sos, sig)
ax1.plot(t, sig)
ax2.plot(t, filtered)
plt.tight_layout()
plt.show()
}}
}}
}}
=== tell me Yes or No ===
 
{{parW|1=
==== Fonction rapide d'interpolation linéaire - Functor ====
<source lang="python">
{{parW|1=[[Algorithmique#fastLinearInterpolationFunctionAsFonctor|algorithmique]]
def tellmeYesNo( msg ):
    encore = 1
    choices=['y', 'n', 'yes', 'no']
    schoices='/'.join( choices )
    rep=None
    while encore :
        rep=raw_input( msg+'(%s): ' % schoices ).lower()
        encore = not rep in choices
        if encore :
            print "Choices are : '%s'" %( schoices )
    return rep
</source>
}}
}}
== Interface graphique ==
=== [[PyQt]] ===
=== Sous Windows sans console ou terminal  ===
==== ★★★ Méthode avec visual basic ====
{{parW|1=
* créer le fichier {{runNoTerminal.vbs}} avec le contenu :
{{code|lang=vb|code=
CreateObject("Wscript.Shell").Run "textFileNameTool.bat",0,True
}}
Et exécuter ce script en le double-cliquant ou en le lançant depuis une raccourcis.
}}
==== Méthode dans le code avec suppression du terminal  ====
{{parW|1=
* Run Python script without Windows console appearing [https://stackoverflow.com/questions/1689015/run-python-script-without-windows-console-appearing]
{{code|lang=python|code=
class myQtApp( QtWidgets.QMainWindow ):
    def show(self) :
        QtWidgets.QMainWindow.show( self )         
        ########################################################################
        hwnd = ctypes.windll.kernel32.GetConsoleWindow()     
        if hwnd != 0: 
            ctypes.windll.user32.ShowWindow(hwnd, 0)     
            ctypes.windll.kernel32.CloseHandle(hwnd)
            _, pid = win32process.GetWindowThreadProcessId(hwnd)
            os.system('taskkill /PID ' + str(pid) + ' /f')
        ########################################################################
# ...
def main():
    app = QtWidgets.QApplication(sys.argv)
    myapp = myQtApp()
    myapp.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
==== Adapter Rectangle Dans Zone ====
    main()
{{parW|1={{id|AdapterRectangleDansZone}}
}}
* [[Pascal#AdapterRectangleDansZone|Version en Pascal]]
}}
{{codeTr|lang=python|code=
 
def AdapterRectangleDansZone( zone_x,zone_y,zone_l,zone_h, rect_l, rect_h, rlimte ) :
== Exception et Erreurs ==
  if (zone_h > 0 ) and (rect_h>0) :
=== {{id|goodWay}}La bonne façon de gérer les exception pour un débogage ===
      r1 = zone_l / zone_h
{{parW|1=
      r2 = rect_l / rect_h
{{code|lang="python"|code=
      #print r1,r2
#!/usr/bin/python
      if r1 >= r2 :
# -*- coding: UTF-8 -*-
          if rlimte > 0 :
import re, os, sys
              r =  zone_h / rect_h
class CMyException( Exception ) :
              if r > rlimte :
    pass
                  r = rlimte
def raiseCMyException( e, msg ) :
                  hh = round( rect_h*r )
    raise CMyException("\nMyInfo\n"+str(e)).with_traceback(sys.exc_info()[2])
                  ll = round( rect_l*r )
def f1() :  
                  newrect_y = zone_y  +( zone_h-hh ) / 2
        a = int( "1" )
                  newrect_h = hh
        b = int( "1x" )              
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
def f2():
                  newrect_l = ll
    try :
              else :
        f1()
                  hh = zone_h
    except Exception as e :
                  ll = round( zone_h*r2 )
        # old raise CMyException("\nMyInfo\n"+str(e)), None, info[2]              
                  newrect_y = zone_y
        raise CMyException("\nMyInfo\n"+str(e)).with_traceback(sys.exc_info()[2])
                  newrect_h = hh
def f3():
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
    f2()           
                  newrect_l = ll
def f4():
          else :
    f3()      
            hh = zone_h
try :
            ll = round( zone_h*r2 )
    f4()
            newrect_y = zone_y
except Exception as e :
            newrect_h = hh
    raise CMyException("\nMyInfo in main\n"+str(e)).with_traceback(sys.exc_info()[2])
            newrect_x = zone_x  + (zone_l-ll) / 2
}}
             newrect_l = ll
Ce qui donne :
      else :
{{code|lang="text"|code=
          if rlimte > 0 :
Traceback (most recent call last):
              r =  zone_l / rect_l
  File "exception.py", line 23, in <module>
              if r > rlimte :
    f4()
                  r = rlimte
  File "exception.py", line 21, in f4
                  hh = round( rect_h*r )
    f3()       
                  ll = round( rect_l*r )
  File "exception.py", line 19, in f3
                  newrect_y = zone_y  +( zone_h-hh ) / 2
    f2()          
                  newrect_h = hh
  File "exception.py", line 14, in f2
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
    f1()
                  newrect_l = ll
   File "exception.py", line 11, in f1
              else :
    b = int( "1x" )               
                  ll = zone_l
__main__.CMyException:
                  hh = round( ll/r2 )
MyInfo in main
                  newrect_x = zone_x
                  newrect_l = ll
                  newrect_y = zone_y  + ( zone_h-hh ) / 2
                  newrect_h = hh
          else :
              ll = zone_l
              hh = round( ll/r2 )
              newrect_x = zone_x
              newrect_l = ll
              newrect_y = zone_y  + ( zone_h-hh ) / 2
              newrect_h = hh
   else :
      newrect_x = zone_x
      newrect_l = 0
      newrect_y = zone_y
      newrect_h = 0


MyInfo
  return newrect_x,newrect_y,newrect_l,newrect_h
invalid literal for int() with base 10: '1x'
}}
}}  
}}
}}


=== error_in_function ===
==== Fonction de comparaison pour les tri : sort ====
===== Avec python 2 =====
{{parW|1=
{{parW|1=
<source lang="python">
La comparaison suivante range dans l'ordre des valeurs croissantes:
def error_in_function( msg, niv=1 ):
{{code|lang=python|code=
     fonction_name  = sys._getframe(niv).f_code.co_name
def myCmp(pntA, pntB):
     raise Exception( "Error : %s : %s" %( fonction_name, msg )  )
     rc = 0
</source>
     if pntA < pntB:
        rc = -1
    elif pntA > pntB:
        rc = 1
    return rc
 
vals = [ 1, 5, 6, 0, -15 ]
vals.sort(myCmp)
print vals
}}
}}
=== param_isnot_set ===
ce qui donne :
{{parW|1=
{{code|lang=python|code=
<source lang="python">
[-15, 0, 1, 5, 6]
def param_isnot_set( param, param_name ):
    if param == None :
        error_in_function( "%s is not set" % param_name, niv=2 )
</source>
}}
}}
=== param_isnot_file ===
{{parW|1=
<source lang="python">
def param_isnot_file( pathfilename ):
    if not os.path.isfile( pathfilename ) :
        error_in_function( "'%s' is not a file" % pathfilename, niv=2 )
</source>
}}
}}
=== param_isnot_dir ===
===== Avec Python 3 =====
{{parW|1=
{{parW|1=
<source lang="python">
Le tri se fait dans l'ordre croissant !
def param_isnot_dir( pathdirname ):
 
    if not os.path.isdir( pathdirname ) :
Pour les tuples ou listes imbriqués, tri sur l'indice n
        error_in_function( "'%s' is not a dir" % pathdirname, niv=2 )
{{code|lang=python|code=
</source>
myList = sorted(myList, key = lambda els: els[n])
}}
}}


== Fichiers et répertoires ==
{{code|lang=python|code=
=== Obtenir le contenu d'un répertoire à la manière de Linux ===
sprocketTeethPointList1.sort( key = lambda pnt: pnt.angle)
{{parW|1=
{{code|colNb=80|lang="python"|code=
import glob
for path in glob.glob("/home/C07138/.*")+glob.glob( "/home/C07138/*" ) :
    print path
}}
}}
ou
{{code|lang=python|code=
sprocketTeethPointList1 = sorted(sprocketTeethPointList1,
                            key = lambda pnt: pnt.angle)
}}
}}
=== Liste des répertoires ===
ou
{{parW|1=
{{code|lang=python|code=
{{code|colNb=80|lang="python"|code=
def angledPointKey(key ):
#!/usr/bin/python
    return key.angle
# -*- coding: ISO8859-1 -*-
import os, sys, re


def tofile( filename, text ) :
sprocketTeethPointList1 = sorted(sprocketTeethPointList1, key = angledPointKey )
    f = open(filename, "w")
}}
    f.write(text)
    f.close()


if __name__ == '__main__' :  
ou
     fs0 = os.listdir('.')
{{code|lang=python|code=
     fs=list()
def cmpIntAPy3( aa ):
    for x in fs0 :
     a = aa.serviceDate
         fs.append(x.lower())
     if a == None :
      
         a = aa.prototypeDate   
    fs.sort()
     return a
    s=''
 
    for x in fs :
self.intAs = sorted(self.intAs, key = cmpIntAPy3 )
        if os.path.isdir( x ) :
            s+=x.lower()+" "
    tofile( 'dir_list.txt', s )  
}}
}}
}}
}}
=== Personnaliser "file object" ===
 
===== Avec Python 3 à la manière de Python 2=====
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|lang=python|code=
class myFileObject :
def angledPointClass( myCmpFunc ) :
    def __init__( self, filename, mode="r" ) :
    class K :
        self.f = open(filename,mode)
        def __init__(self, obj, *args):
 
            self.obj = obj
    def close(self) :
        def __lt__(self, other):
        return self.f.close()
            return myCmpFunc(self.obj, other.obj) < 0
 
        def __gt__(self, other):
    def read( self ) :
            return myCmpFunc(self.obj, other.obj) > 0
        txt = self.f.read().replace('\n\r','\n').replace('\r\n','\n').replace('\r','\n')
        def __eq__(self, other):
        return txt
            return myCmpFunc(self.obj, other.obj) == 0
        def __le__(self, other):
            return myCmpFunc(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return myCmpFunc(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return myCmpFunc(self.obj, other.obj) != 0
    return K       


    def write( self, txt ) :
def angledPointCmp(pntA, pntB):
         #txt = txt.replace('\n','\r')
    rc = 0
         return self.f.write( txt )
    pntA = pntA.angle
    pntB = pntB.angle
    if pntA < pntB:
         rc = -1
    elif pntA > pntB:
         rc = 1
    return rc 


def omypen( filename, mode="r" ) :
sprocketTeethPointList1.sort( key=angledPointClass(angledPointCmp) )
    return myFileObject( filename, mode )
}}
}}
}}
}}
=== Lire un fichier ligne par ligne ===
 
== Clavier, Input device ==
=== get_char ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
voir {{m|curses.window.getch()}} pour une implémentation sous linux.
import codecs
<source lang="python">
ENCODING = "UTF-8"
if os.name=="nt" :
with codecs.open(param.csvFileName, "r", ENCODING) as csvSrc:
    import msvcrt
    with codecs.open(csvDstName, "w", ENCODING) as csvDst:
    def get_char() :
        lineNumber = 0
        if msvcrt.kbhit() :
         for line in csvSrc:
            return msvcrt.getch()
             line = line.replace("\n","").replace("\r","")
         else :
            lineNumber += 1
             return None
else :
    print "Error : No get_char()"
    exit(1)
</source>
}}
}}
=== tell me Yes or No ===
{{parW|1=
<source lang="python">
def tellmeYesNo( msg ):
    encore = 1
    choices=['y', 'n', 'yes', 'no']
    schoices='/'.join( choices )
    rep=None
    while encore :
        rep=raw_input( msg+'(%s): ' % schoices ).lower()
        encore = not rep in choices
        if encore :
            print "Choices are : '%s'" %( schoices )
    return rep
</source>
}}
}}
=== tofile fromfile ===
== Interface graphique ==
=== [[PyQt]] ===
=== Sous Windows sans console ou terminal  ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
* voir [[Introduction au MS-DOS|noTerminal]]
import codecs
}}
ENCODING = "UTF-8"
 
def toTextFile(filename, text):
== Exception et Erreurs ==
    with codecs.open(filename, "w", ENCODING) as fileDesc:
=== {{id|goodWay}}La bonne façon de gérer les exception pour un débogage ===
        fileDesc.write(text)
 
def fromTextFile(filename):
    text = None
    with codecs.open(filename, "r", ENCODING) as fileDesc:
        text = fileDesc.read()
    return text
 
 
def fromTextFileWin(filename):
    text = None
    try :
        with codecs.open(filename, "r", ENCODING) as fileDesc:
            text = fileDesc.read()
    except Exception as e :
        print("Warning %s" % e)
        print("try %s" % ENCODING2)
        with codecs.open(filename, "r", ENCODING2) as fileDesc:
            text = fileDesc.read()
    return text
 
 
}}
}}
 
=== Lire des fichiers ini ===
 
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|lang="python"|code=
#!/usr/bin/python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
#***********************************************************
import re, os, sys
# Author:   Arthur TOROSSIAN
class CMyException( Exception ) :
# Date:   30.10.2017
    pass
#***********************************************************/
def raiseCMyException( e, msg ) :
import configparser
    raise CMyException("\nMyInfo\n"+str(e)).with_traceback(sys.exc_info()[2])
ABSTRACT_MSG = "call of abstract method"
def f1() :  
################################################################################
        a = int( "1" )
class CIniFileError(Exception):
        b = int( "1x" )               
    """\
def f2():
    the main exception class of the module
     try :
    """
        f1()
    pass
     except Exception as e :
 
        # old raise CMyException("\nMyInfo\n"+str(e)), None, info[2]            
def str2bool(v):
         raise CMyException("\nMyInfo\n"+str(e)).with_traceback(sys.exc_info()[2])
     v = v.strip().lower()
def f3():
     if not v in ["true", "false", "vrai", "faux"]:
    f2()           
         raise CIniFileError("v='%s' is not a valid boolean" % v)
def f4():
    return (v in ["true", "vrai"])
    f3()       
 
try :
################################################################################
     f4()
# CIniParam in order to read ini files
except Exception as e :
################################################################################
     raise CMyException("\nMyInfo in main\n"+str(e)).with_traceback(sys.exc_info()[2])
class CIniParam:
}}
     ############################################################################
Ce qui donne :
     def __init__(self):
{{code|lang="text"|code=
        self.fileName = None
Traceback (most recent call last):
        self.config = None
  File "exception.py", line 23, in <module>
        self._currentSection = None
     f4()
     ############################################################################
  File "exception.py", line 21, in f4
     def loadParam(self, fileName):
     f3()      
        self.fileName = fileName
  File "exception.py", line 19, in f3
        self.config = configparser.ConfigParser()
    f2()          
        self.config.read(fileName)
  File "exception.py", line 14, in f2
        self.getParamFromConfig()
    f1()
  File "exception.py", line 11, in f1
    b = int( "1x" )              
__main__.CMyException:
MyInfo in main


    def getParamFromConfig(self):
MyInfo
        """\
invalid literal for int() with base 10: '1x'
        (API) abstract required API method
}}
        Check all options and attributes validity.
}}
        """
        raise CIniFileError(ABSTRACT_MSG)


    def checkVersion(self, formatSection, v01, v02, v03):
=== error_in_function ===
        self.setCurrentSection(formatSection)
{{parW|1=
        v1 = self.getInt("v1")
<source lang="python">
        v2 = self.getInt("v2")
def error_in_function( msg, niv=1 ):
        v3 = self.getInt("v3")
    fonction_name  = sys._getframe(niv).f_code.co_name
        if v1 != v01 :
    raise Exception( "Error : %s : %s" %( fonction_name, msg ) )
            errMsg = """
</source>
 
}}
ERROR the file named '%s', in section named '%s', has no the right file format
=== param_isnot_set ===
version. The version must be %d.x.x and the current version is %d.%d.%d
{{parW|1=
""" % (self.fileName, formatSection, v01, v1, v2, v3)
<source lang="python">
            raise CIniFileError(errMsg)
def param_isnot_set( param, param_name ):
 
    if param == None :
    def hasTheSection(self):
        error_in_function( "%s is not set" % param_name, niv=2 )
        return self.config.has_section(self._currentSection)
</source>
 
}}
    def hasOption(self, optionName):
=== param_isnot_file ===
         return self.config.has_option(self._currentSection, optionName)
{{parW|1=
    ############################################################################
<source lang="python">
    def setCurrentSection(self, currentSection):
def param_isnot_file( pathfilename ):
        self._currentSection = currentSection
    if not os.path.isfile( pathfilename ) :
        if not self.hasTheSection():
         error_in_function( "'%s' is not a file" % pathfilename, niv=2 )
            errMsg = """
</source>
}}
=== param_isnot_dir ===
{{parW|1=
<source lang="python">
def param_isnot_dir( pathdirname ):
    if not os.path.isdir( pathdirname ) :
        error_in_function( "'%s' is not a dir" % pathdirname, niv=2 )
</source>
}}


ERROR the file named '%s', has no section named '%s'
== Fichiers et répertoires ==
""" % (
=== Obtenir le contenu d'un répertoire à la manière de Linux ===
                    self.fileName, self._currentSection)
{{parW|1=
            raise CIniFileError(errMsg)
{{code|colNb=80|lang="python"|code=
 
import glob
 
for path in glob.glob("/home/C07138/.*")+glob.glob( "/home/C07138/*" ) :
    def getFloat(self, varName):
    print path
        val = self.loadParamFloat(self._currentSection, varName)
}}
        return val
}}
=== Liste des répertoires ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/python
# -*- coding: ISO8859-1 -*-
import os, sys, re


    def getFloatList(self, varName):
def tofile( filename, text ) :
        valList = eval(self.loadParamStr(self._currentSection, varName))
    f = open(filename, "w")
        newVal = list()
    f.write(text)
        for sf in valList :
    f.close()
            newVal.append(float(sf))
        return newVal


     def getFloatOrNoneList(self, varName):
if __name__ == '__main__' :   
         valList = eval(self.loadParamStr(self._currentSection, varName))
    fs0 = os.listdir('.')
        newVal = list()
     fs=list()
        for sf in valList :
    for x in fs0 :
            if sf == None :
         fs.append(x.lower())
                newVal.append(sf)
   
            else:
    fs.sort()
                newVal.append(float(sf))
    s=''
         return newVal
    for x in fs :
        if os.path.isdir( x ) :
            s+=x.lower()+" "
    tofile( 'dir_list.txt', s )  
}}
}}
=== Personnaliser "file object" ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
class myFileObject :
    def __init__( self, filename, mode="r" ) :
         self.f = open(filename,mode)


     def getStrList(self, varName):
     def close(self) :
         valList = eval(self.loadParamStr(self._currentSection, varName))
         return self.f.close()
        newVal = list()
        for sf in valList :
            newVal.append(sf)
        return newVal


     def getInt(self, varName):
     def read( self ) :
         val = self.loadParamInt(self._currentSection, varName)
         txt = self.f.read().replace('\n\r','\n').replace('\r\n','\n').replace('\r','\n')
         return val
         return txt


     def getBool(self, varName):
     def write( self, txt ) :
         val = self.loadParamBool(self._currentSection, varName)
         #txt = txt.replace('\n','\r')
         return val
         return self.f.write( txt )


     def getStr(self, varName):
def omypen( filename, mode="r" ) :
         val = self.loadParamStr(self._currentSection, varName)
     return myFileObject( filename, mode )
         return val
}}
}}
=== Lire un fichier caractère  par caractère ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
with open(filename, "r", "UTF-8") as f:
    while True:
        c = f.read(1)
        if not c:
            print("End of file")
            break
         print("Read a character:", c)
}}
}}
=== Lire un fichier ligne par ligne ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
import codecs
ENCODING = "UTF-8"
with codecs.open(param.csvFileName, "r", ENCODING) as csvSrc:
    with codecs.open(csvDstName, "w", ENCODING) as csvDst:
        lineNumber = 0
         for line in csvSrc:
            line = line.replace("\n","").replace("\r","")
            lineNumber += 1
}}
}}


    ############################################################################
=== tofile fromfile ===
    def checkNoParam(self, paramName):
{{parW|1=
         if not self.hasOption(paramName):
{{code|colNb=80|lang="python"|code=
            errMsg = """
encoding = "UTF-8"
def toTextFile(filename, text):
    with open(filename, "w", encoding=encoding) as fileDesc:
         fileDesc.write(text)
 
def fromTextFile(filename):
    text = None
    with open(filename, "r", encoding=encoding) as fileDesc:
        text = fileDesc.read()
    return text


ERROR the file named '%s', in section named '%s', has no parameter named '%s'
""" % (self.fileName, self._currentSection, paramName)
            raise CIniFileError(errMsg)


    def loadParamFloat(self, sectionName, varName):
def fromTextFileWin(filename):
         self.checkNoParam(varName)
    text = None
        xs = self.config.get(sectionName, varName).split("#")[0]
    try :  
         x = float(eval(xs))
         with codecs.open(filename, "r", ENCODING) as fileDesc:
        return x
            text = fileDesc.read()
    except Exception as e :
        print("Warning %s" % e)
         print("try %s" % ENCODING2)
        with codecs.open(filename, "r", ENCODING2) as fileDesc:
            text = fileDesc.read()
    return text


    def loadParamInt(self, sectionName, varName):
}}
        self.checkNoParam(varName)
}}
        x = int(self.config.get(sectionName, varName).split("#")[0])
        return x


    def loadParamBool(self, sectionName, varName):
=== Lire des fichiers ini ===
        self.checkNoParam(varName)
        dat = self.config.get(sectionName, varName)
        x = str2bool(dat.split("#")[0])
        return x


    def loadParamStr(self, sectionName, varName):
{{parW|1=
        self.checkNoParam(varName)
        x = self.config.get(sectionName, varName).split("#")[0]
        return x
}}
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
class CParams(CIniParam) :
#!/usr/bin/python
    def getParamFromConfig(pm):
# -*- coding: UTF-8 -*-
        pm.setCurrentSection("param")
#***********************************************************
        pm.tMax = pm.getFloat("p1")
# Author:   Arthur TOROSSIAN
}}
# Date:    30.10.2017
}}
#***********************************************************/
=== fichiers temporaires, tmp, temp ===
import configparser
ABSTRACT_MSG = "call of abstract method"
################################################################################
class CIniFileError(Exception):
    """\
    the main exception class of the module
    """
    pass


{{parW|1=
def str2bool(v):
{{code|colNb=80|lang="python"|code=
    v = v.strip().lower()
tmp_file=tempfile.NamedTemporaryFile( delete=False )
    if not v in ["true", "false", "vrai", "faux"]:
tmp_file.close()
        raise CIniFileError("v='%s' is not a valid boolean" % v)
print tmp_file.name
    return (v in ["true", "vrai"])
print os.path.exists(tmp_file.name)
tgzs=fromfile( tmp_file.name )
s.unlink(tmp_file.name)
print os.path.exists(tmp_file.name)
}}
}}


=== Lire et écrire des binaires (endianness; little-endian et big-endian) dans des fichiers ===
################################################################################
{{parW|1=
# CIniParam in order to read ini files
On utilise le module {{m|struct}} avec les méthodes {{m|unpack}} et {{m|pack}} :
################################################################################
{{code|colNb=80|lang="python"|code=
class CIniParam:
def scanDatFile( fileName, fileDestinationName, endianness='<', ee1WaterDeep=5, ee1LandHeight=10 ) :
    ############################################################################
    bs = os.path.getsize( fileName )
    def __init__(self):
    fsize = 0   
        self.fileName = None
    fic = open( fileName , 'rb')
        self.config = None
    ficDest = open( fileDestinationName , 'wb')
        self._currentSection = None
     # < little-endian BYTEORDER LSBFIRST
     ############################################################################
    # > big-endian
     def loadParam(self, fileName):
    # h short integer 2 bytes
         self.fileName = fileName
     fmt = "%sh" % endianness
         self.config = configparser.ConfigParser()
    min = 60000
         self.config.read(fileName)
    max = -60000
         self.getParamFromConfig()
    noval=-32768
 
    while fsize < bs :
     def getParamFromConfig(self):
         fsize += 2
        """\
         tmp = fic.read( struct.calcsize(fmt) )
        (API) abstract required API method
        val, = struct.unpack( fmt , tmp  )  
        Check all options and attributes validity.
         valBin = struct.pack( fmt , func.hcorection( val )
        """
         ficDest.write( valBin )       
        raise CIniFileError(ABSTRACT_MSG)
        #print val
        if val != noval :
            if val < min :
                min = val
            if val > max :
                max = val
    print min, max
    ee1 = ee1WaterDeep + ee1LandHeight
    map = float(max-min+1)
    ee2map = map / ee1
     ee1WaterDeep = round( min/ee2map )
    ee1LandHeight = round( max/ee2map )
    print "Water Deep:%s Land height: %s" %( round( min/ee2map ), round( max/ee2map )  )
    print "Water Cutoff:%s Land Cutoff: %s" %( round( ee1WaterDeep*ee2map ), round( ee1LandHeight*ee2map )  )
    ficDest.close()
    fic.close()
}}
}}
=== Lire et écrire des fichiers netCDF ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
}}
* Read and Write netCDF Files
*: https://pythonhosted.org/landlab/landlab.io.netcdf.html
}}


=== Copier les dates d'un fichier à un autre ===
    def checkVersion(self, formatSection, v01, v02, v03):
{{parW|1=
        self.setCurrentSection(formatSection)
{{code|colNb=80|lang="python"|code=
        v1 = self.getInt("v1")
st=os.stat( file1 )
        v2 = self.getInt("v2")
os.utime( file2, (st.st_atime, st.st_mtime) )
        v3 = self.getInt("v3")
}}
        if v1 != v01 :
}}
            errMsg = """
=== trace ===
 
{{parW|1=
ERROR the file named '%s', in section named '%s', has no the right file format
{{code|colNb=80|lang="python"|code=
version. The version must be %d.x.x and the current version is %d.%d.%d
def get_datetime_str():
""" % (self.fileName, formatSection, v01, v1, v2, v3)
    return time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
            raise CIniFileError(errMsg)
 
    def hasTheSection(self):
        return self.config.has_section(self._currentSection)


trace_file_name="trace.txt"
    def hasOption(self, optionName):
def trace( msg, init=0 ) :
        return self.config.has_option(self._currentSection, optionName)
    filename = trace_file_name
     ############################################################################
    if (os.path.exists( filename ) and (init==0) ):
     def setCurrentSection(self, currentSection):
        f = open( filename, "a"  )
        self._currentSection = currentSection
    else :
         if not self.hasTheSection():
        f = open( filename, "w"  )
            errMsg = """
     f.write( "%s %s\n" % (get_datetime_str(),msg) )
     f.close()
trace( "INIT", init=1 )
}}
}}
=== get_NewFileName ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
def get_NewFileName( name, Index=1 ) :
    newname = name   
    name, ext = os.path.splitext( newname  )
    while os.path.exists( newname ) :       
        newname = name + ("%03d" % Index) + ext
         Index += 1
    return newname, Index
}}
}}
=== get_NewDictName ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
patName = re.compile("^(.*?)(\d*)$")
def normName( name  ) :
    nname, ni = patName.findall( name )[0]
    if ni != "" :
        i = int( ni )
        newname = nname + ("%03d" % i)


    else :
ERROR the file named '%s', has no section named '%s'
        newname = name
""" % (
    return newname
                    self.fileName, self._currentSection)
            raise CIniFileError(errMsg)


def normDictNames( namedict ) :
    newD = dict()
    for name, val in namedict.items() :
        newname = normName( name  )
        newD[ newname ] = val
    return newD


def get_NewDictName( name, namedict, Index=1 ) :
    def getFloat(self, varName):
    newname = name
        val = self.loadParamFloat(self._currentSection, varName)
    name, i = patName.findall( newname )[0]
         return val
    while newname in namedict :
 
         newname = name + ("%03d" % Index)
     def getFloatList(self, varName):
        Index += 1
        valList = eval(self.loadParamStr(self._currentSection, varName))
     return newname, Index
        newVal = list()
}}
        for sf in valList :
utilisation possible  :
            newVal.append(float(sf))
{{code|colNb=80|lang="python"|code=
        return newVal
dd0 = {"otto":1,"toto3":2, "toto02":4, "tata":5, "toto" :1 }
print dd0
dd = normDictNames( dd0 )
print dd
name, index = get_NewDictName( "toto", dd  )
dd[name] = 30
print name, index, dd
name, index = get_NewDictName( "toto", dd  )
dd[name] = 15
print name, index, dd
}}


{{code|colNb=80|lang="python"|code=
    def getFloatOrNoneList(self, varName):
{'tata': 5, 'toto': 1, 'toto02': 4, 'toto3': 2, 'otto': 1}
        valList = eval(self.loadParamStr(self._currentSection, varName))
{'toto': 1, 'tata': 5, 'toto002': 4, 'toto003': 2, 'otto': 1}
        newVal = list()
toto001 2 {'toto003': 2, 'tata': 5, 'toto': 1, 'toto002': 4, 'toto001': 30, 'otto': 1}
        for sf in valList :
toto004 5 {'toto003': 2, 'tata': 5, 'toto004': 15, 'toto': 1, 'toto002': 4, 'toto001': 30, 'otto': 1}
            if sf == None :
}}
                newVal.append(sf)
}}
            else:
=== path_split ===
                newVal.append(float(sf))
{{parW|1=
        return newVal
{{code|colNb=80|lang="python"|code=
 
def path_split( pathnameext ):
    def getStrList(self, varName):
    path, name = os.path.split( pathnameext )
        valList = eval(self.loadParamStr(self._currentSection, varName))
    name , ext = os.path.splitext( name )
        newVal = list()
    return (path, name, ext,)
        for sf in valList :
}}
            newVal.append(sf)
}}
        return newVal
=== change_path_and_suffix ===
 
{{parW|1=
    def getInt(self, varName):
{{code|colNb=80|lang="python"|code=
        val = self.loadParamInt(self._currentSection, varName)
def change_path_and_suffix( pathnameext, newpath, suffix ) :
        return val
    path, nameext = os.path.split( pathnameext )
 
    name, ext = os.path.splitext( nameext )
    def getBool(self, varName):
    return newpath + os.sep + name+suffix+ext
        val = self.loadParamBool(self._currentSection, varName)
}}
        return val
}}
 
=== change_path_and_ext ===
     def getStr(self, varName):
{{parW|1=
         val = self.loadParamStr(self._currentSection, varName)
{{code|colNb=80|lang="python"|code=
        return val
def change_path_and_ext( pathnameext, newpath, ext ) :
    path, nameext = os.path.split( pathnameext )
    name, ext0 = os.path.splitext( nameext )
    return newpath + os.sep + name+ext
}}
}}
=== Get list of files ===
{{parW|1=
Simple :
{{code|colNb=80|lang="python"|code=
def findFilesInDirectorFromPattern( path, pat ) :
    flist = list()  
     fs = os.listdir(path)
    for x in fs :
         file_path = path+os.sep+x
        if os.path.isfile( file_path  ) :
            if pat.match( x ) :
                flist.append( file_path  )
    return flist   
}}


Évoluée :
    ############################################################################
{{code|colNb=80|lang="python"|code=
    def checkNoParam(self, paramName):
def find( flist, path, file_pattern,  subdir, file_exclude_pattern=None, dir_exclude_pattern=None ) :
         if not self.hasOption(paramName):
    fs = os.listdir(path)
             errMsg = """
    for x in fs :
        file_path = path+os.sep+x
         if os.path.isfile( file_path  ) :
            ok=1
            if file_exclude_pattern != None :
                ok = not file_exclude_pattern.match( x )
            if ok and file_pattern.match( x ) :
                print x
                flist.append( file_path  )
        if os.path.isdir( file_path  ) :
             if subdir :
                ok = 1
                if dir_exclude_pattern != None :
                    ok= not dir_exclude_pattern.match( x )
                if ok :
                    find( flist, file_path, file_pattern,  subdir, file_exclude_pattern, dir_exclude_pattern)
}}
}}
=== Générer une fichier html à partir d'une liste de fichiers sur disques gen_list_html ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/env python
import re
import os
def gen_list_html( path, file_pattern_txt ) :
    file_pattern = re.compile( file_pattern_txt )
    fs = os.listdir(path)
    fs.sort()
    print "<html><body><ol>"
    for x in fs :
        file_path = path+os.sep+x
        if os.path.isfile( file_path  ) :
            if file_pattern.match( x ) :
                print "<li><a href='%s'>%s</a></li>" %(x,x)


    print "</ol></body></html>"
ERROR the file named '%s', in section named '%s', has no parameter named '%s'
if __name__ == '__main__' :
""" % (self.fileName, self._currentSection, paramName)
    gen_list_html( ".", ".*\.avi$" )
            raise CIniFileError(errMsg)
}}
}}
=== Générer une fichier html à partir d'une liste d'images/photo sur disques ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys, re, codecs, time, shutil


    def loadParamFloat(self, sectionName, varName):
        self.checkNoParam(varName)
        xs = self.config.get(sectionName, varName).split("#")[0]
        x = float(eval(xs))
        return x


srcPath = "."
    def loadParamInt(self, sectionName, varName):
fl = os.listdir(srcPath)
        self.checkNoParam(varName)
sorted(fl)
        x = int(self.config.get(sectionName, varName).split("#")[0])
        return x


f = codecs.open("index.html", "w", encoding = "UTF-8")
    def loadParamBool(self, sectionName, varName):
        self.checkNoParam(varName)
        dat = self.config.get(sectionName, varName)
        x = str2bool(dat.split("#")[0])
        return x


f.write("<html style='background-color:#a0a0a0;margin:auto;'>\n")
    def loadParamStr(self, sectionName, varName):
 
        self.checkNoParam(varName)
f.write("""<body
        x = self.config.get(sectionName, varName).split("#")[0]
style='width:210mm;margin:auto;padding:5mm;background-color:#ffffff;'>
        return x
<style type="text/css">
}}
p.p {
{{code|colNb=80|lang="python"|code=
width:180mm;background-color:#ffffff;margin:auto;
class CParams(CIniParam) :
}
    def getParamFromConfig(pm):
td.g {
        pm.setCurrentSection("param")
width:30mm; vertical-align:middle;
        pm.tMax = pm.getFloat("p1")
}
}}
td.d {
}}
width:150mm; vertical-align:top; background-color:#ffffff;font-size:10pt;
=== fichiers temporaires, tmp, temp ===
}
img{
width:28mm;
}
</style>
<p class="p">
<table align=center>
""")


for img in fl :
{{parW|1=
    name, ext = os.path.splitext(img)
{{code|colNb=80|lang="python"|code=
    print(name.lower())
tmp_file=tempfile.NamedTemporaryFile( delete=False )
    if ext.lower() == ".jpg" :
tmp_file.close()
        f.write("""\
print tmp_file.name
<tr>
print os.path.exists(tmp_file.name)
    <td class='g'> <img src='%s'> </td>
tgzs=fromfile( tmp_file.name )
    <td class='d'> TODO </td>
s.unlink(tmp_file.name)
</tr>
print os.path.exists(tmp_file.name)
""" % img)
 
f.write("""
</table>
</p>
</body>
""")
f.write("</html>\n")
 
f.close()
}}
}}
}}
}}


=== gen m3u - liste de mp3 - player list ===
=== Lire et écrire des binaires (endianness; little-endian et big-endian) dans des fichiers ===
{{parW|1=
{{parW|1=
On utilise le module {{m|struct}} avec les méthodes {{m|unpack}} et {{m|pack}} :
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
import re
def scanDatFile( fileName, fileDestinationName, endianness='<', ee1WaterDeep=5, ee1LandHeight=10 ) :
import os
     bs = os.path.getsize( fileName )  
import codecs
     fsize = 0   
encoding = "latin1"
     fic = open( fileName , 'rb')
     ficDest = open( fileDestinationName , 'wb')
def tofile( filename, text ) :
     # < little-endian BYTEORDER LSBFIRST
     f = codecs.open(filename, "w", encoding)
     # > big-endian
     f.write(text)
     # h short integer 2 bytes
     f.close()
     fmt = "%sh" % endianness
      
     min = 60000
def gen_list( path, file_pattern_txt ) :
     max = -60000
     file_pattern = re.compile( file_pattern_txt )
    noval=-32768
     fs = os.listdir(path)
    while fsize < bs :
     fs.sort()
         fsize += 2
     m3u=u""
        tmp = fic.read( struct.calcsize(fmt) )
      
        val, = struct.unpack( fmt , tmp  )   
     for x in fs :
         valBin = struct.pack( fmt , func.hcorection( val ) )  
         file_path = path+os.sep+x
        ficDest.write( valBin )       
         if os.path.isfile( file_path ) :
        #print val
             if file_pattern.match( x ) :
        if val != noval :
                 m3u += u"%s\r\n" %(x)
             if val < min :
     tofile( "arno.m3u" , m3u )
                min = val
   
            if val > max :
if __name__ == '__main__' :
                 max = val
     gen_list( u".", u".*\.mp3$" )
    print min, max
    ee1 = ee1WaterDeep + ee1LandHeight
    map = float(max-min+1)
    ee2map = map / ee1
    ee1WaterDeep = round( min/ee2map )
    ee1LandHeight = round( max/ee2map )
    print "Water Deep:%s Land height: %s" %( round( min/ee2map ), round( max/ee2map )  )
     print "Water Cutoff:%s Land Cutoff: %s" %( round( ee1WaterDeep*ee2map ), round( ee1LandHeight*ee2map )
    ficDest.close()
     fic.close()
}}
}}
}}
}}
=== gen m3u8 - liste de mp3 - player list ===
=== Lire et écrire des fichiers netCDF ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/python
}}
# -*- coding: UTF-8 -*-
* Read and Write netCDF Files
import re,os, codecs
*: https://pythonhosted.org/landlab/landlab.io.netcdf.html
encoding = "UTF8"
}}


def tofile( filename, text ) :
=== Copier les dates d'un fichier à un autre ===
    f = codecs.open(filename, "w", encoding)
{{parW|1=
    f.write(text)
{{code|colNb=80|lang="python"|code=
    f.close()
st=os.stat( file1 )
   
os.utime( file2, (st.st_atime, st.st_mtime) )
def gen_list( path, file_pattern, level=1 ) :
    # file_pattern = re.compile( file_pattern_txt )
    fs = os.listdir(path)
    fs.sort()
    m3u=u""  
    for x in fs :
        file_path = path+os.sep+x
        if os.path.isfile( file_path  ) :
            if file_pattern.match( x ) :
                m3u +=  u"%s\r\n" %(file_path)              
        if os.path.isdir( file_path  ) :
            m3u +=  gen_list( file_path, file_pattern, level=level+1 )           
    if level == 1 :       
        tofile( "all.m3u8" , m3u )       
    return m3u
if __name__ == '__main__' :
    gen_list( u".", re.compile( u".*\.mp3$") )
}}
}}
}}
}}
=== genNewNames  ===
=== trace ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/python
def get_datetime_str():
# -*- coding: UTF-8 -*-
    return time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
import os, sys, re, random


def get_NewFileName( name, Index=1 ) :
trace_file_name="trace.txt"
     newname = name     
def trace( msg, init=0 ) :
     name, ext = os.path.splitext( newname  )
    filename = trace_file_name
    if (os.path.exists( filename ) and (init==0) ):
        f = open( filename, "a"  )
    else :
        f = open( filename, "w"  )
    f.write( "%s %s\n" % (get_datetime_str(),msg) )
    f.close()
trace( "INIT", init=1 )
}}
}}
=== get_NewFileName ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
def get_NewFileName( name, Index=1 ) :
     newname = name     
     name, ext = os.path.splitext( newname  )
     while os.path.exists( newname ) :         
     while os.path.exists( newname ) :         
         newname = name + ("%03d" % Index) + ext
         newname = name + ("%03d" % Index) + ext
         Index += 1
         Index += 1
     return newname, Index
     return newname, Index
}}
}}
=== get_NewDictName ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
patName = re.compile("^(.*?)(\d*)$")
def normName( name  ) :
    nname, ni = patName.findall( name )[0]
    if ni != "" :
        i = int( ni )
        newname = nname + ("%03d" % i)
    else :
        newname = name
    return newname


def genNewNames( path ) :
def normDictNames( namedict ) :
     index=1
     newD = dict()
    fs = os.listdir(path)
     for name, val in namedict.items() :
     nb = len(fs)
         newname = normName( name  )
    num = 0
         newD[ newname ] = val
    while nb > 0 :
    return newD
         i = random.randint(0, nb-1 )
 
         nname = path+os.sep+fs[i]
def get_NewDictName( name, namedict, Index=1 ) :
        del fs[i]
    newname = name
        if os.path.isfile( nname ) :
     name, i = patName.findall( newname )[0]
            nname0, ext = os.path.splitext(nname)
     while newname in namedict :
            pname, nname0 = os.path.split(nname)
         newname = name + ("%03d" % Index)
            rname = pname + os.sep+"im%05d%s" % (num,ext)
         Index += 1
            print "  ",nname, rname
     return newname, Index
            rname, index = get_NewFileName( rname, index )
            os.rename( nname , rname )       
        num += 1
        nb -= 1
       
def genNewNamesInSubDirs( path ) :   
     fs = os.listdir(path)
     for ff in fs :
         pathff = path+os.sep+ff
        print "[%s]" % pathff
         if os.path.isdir( pathff ) :
            genNewNames( pathff )
if __name__ == u'__main__' :   
     genNewNamesInSubDirs( "./Images/listes") 
    genNewNames( "./Images/listeAll" )
}}
}}
}}
=== unix2dos ===
utilisation possible  :
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/env python
dd0 = {"otto":1,"toto3":2, "toto02":4, "tata":5, "toto" :1 }
###############
print dd0
import sys
dd = normDictNames( dd0 )
print dd
name, index = get_NewDictName( "toto", dd  )
dd[name] = 30
print name, index, dd
name, index = get_NewDictName( "toto", dd  )
dd[name] = 15
print name, index, dd
}}


for fname in sys.argv[1:]:
{{code|colNb=80|lang="python"|code=
    infile = open( fname, "rb" )
{'tata': 5, 'toto': 1, 'toto02': 4, 'toto3': 2, 'otto': 1}
    instr = infile.read()
{'toto': 1, 'tata': 5, 'toto002': 4, 'toto003': 2, 'otto': 1}
    infile.close()
toto001 2 {'toto003': 2, 'tata': 5, 'toto': 1, 'toto002': 4, 'toto001': 30, 'otto': 1}
    outstr = instr.replace( "\r\n", "\n" ).replace( "\n\r", "\n" ).replace( "\r", "\n" ).replace( "\n", "\r\n" )
toto004 5 {'toto003': 2, 'tata': 5, 'toto004': 15, 'toto': 1, 'toto002': 4, 'toto001': 30, 'otto': 1}
 
    if len(outstr) == len(instr):
        continue
   
    outfile = open( fname, "wb" )
    outfile.write( outstr )
    outfile.close()
}}
}}
}}
}}
=== clean_rep.py ===
=== path_split ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/env python
def path_split( pathnameext ):
# -*- coding: iso-8859-1 -*-
     path, name = os.path.split( pathnameext )
import os
     name , ext = os.path.splitext( name )
import re
     return (path, name, ext,)
pat_adir = re.compile( "\d{4}" )
pat_mdir = re.compile( "\d{4}-\d{2}" )
def clean_dirs() :
     """
    Delete empty directories with name like AAAA/AAAA-MM or AAAA.
    """
    adirs = os.listdir(".")
     for adir in adirs :
        if pat_adir.match( adir ) :
            mdirs = os.listdir(adir)
            for mdir in mdirs :
                if pat_mdir.match( mdir ) :
                    files = os.listdir( adir+os.sep+mdir )
                    if len(files)==0 :
                        os.rmdir( adir+os.sep+mdir )
            mdirs = os.listdir(adir)
            if len( mdirs )==0 :
                os.rmdir( adir )
 
if __name__ == '__main__' :
     clean_dirs()
}}
}}
}}
}}
=== gen_rep.py ===
=== change_path_and_suffix ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/env python
def change_path_and_suffix( pathnameext, newpath, suffix ) :
# -*- coding: iso-8859-1 -*-
     path, nameext = os.path.split( pathnameext )
 
    name, ext = os.path.splitext( nameext )
import os
    return newpath + os.sep + name+suffix+ext
 
def gen_dirs() :
     """
    Generate directory with name like AAAA/AAAA-MM if it does not exist.
    """
    for an in range(2000,2012) :
        dir_a = "%04d" %(an)
        if not os.path.exists( dir_a ) :
            os.mkdir( dir_a )
        for m in range(1,13) :
            dir_name = "%s%s%04d-%02d" %(dir_a,os.sep,an,m)
            print dir_name
            if not os.path.exists( dir_name ) :
                os.mkdir( dir_name )
 
if __name__ == '__main__' :
    gen_dirs()
}}
}}
}}
}}
=== size_on_system ===
=== change_path_and_ext ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
def size_on_system( sf, sector_size ):
def change_path_and_ext( pathnameext, newpath, ext ) :
     if sector_size != None :
     path, nameext = os.path.split( pathnameext )
        s=0
     name, ext0 = os.path.splitext( nameext )
        ns = sf % sector_size
     return newpath + os.sep + name+ext
        if ns == 0 :
            s = sf
        else :
            s = (sf / sector_size) * sector_size  + sector_size
     else :
      s=sf
     return s
}}
}}
}}
}}
=== size_of_dir ===
=== Get list of files ===
{{parW|1=
{{parW|1=
Simple :
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
def size_of_dir( path, sector_size=None  ):
def findFilesInDirectorFromPattern( path, pat ) :
     fs = os.listdir( path )
    flist = list()  
    s=0
     fs = os.listdir(path)
     for f in fs :
     for x in fs :
         pf = path+os.sep+f
         file_path = path+os.sep+x
         if os.path.isfile( pf ) :
         if os.path.isfile( file_path  ) :
             statinfo = os.stat( pf )
             if pat.match( x ) :
            s+= size_on_system( statinfo.st_size, sector_size )
                flist.append( file_path )
        if os.path.isdir( pf ) :
     return flist   
            s+=size_of_dir( pf,sector_size )
     return s
}}
}}
}}
 
=== sizeOfFile ===
Évoluée :
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
def sizeOfFile( pathToFile ):
def find( flist, path, file_pattern,  subdir, file_exclude_pattern=None, dir_exclude_pattern=None ) :
     size = None
     fs = os.listdir(path)
     if os.path.isfile( pathToFile ) :
     for x in fs :
         statinfo = os.stat( pathToFile )
        file_path = path+os.sep+x
        size = statinfo.st_size
    return size
        if os.path.isfile( file_path  ) :
            ok=1
            if file_exclude_pattern != None :
                ok = not file_exclude_pattern.match( x )
            if ok and file_pattern.match( x ) :
                print x
                flist.append( file_path  )
         if os.path.isdir( file_path  ) :
            if subdir :
                ok = 1
                if dir_exclude_pattern != None :
                    ok= not dir_exclude_pattern.match( x )
                if ok :
                    find( flist, file_path, file_pattern,  subdir, file_exclude_pattern, dir_exclude_pattern)
}}
}}
}}
}}
=== have_subdir ===
=== Lire et écrire des fichiers HTML ===
{{parW|1=
Il ne faut pas utiliser {{m|html.parser}},  {{m|Simple HTML}} ou {{m|XHTML parser}} mais il est largement recommandé d'utiliser {{m|sgmllib}} ou {{m|Simple SGML parser}}.
}}
=== Générer une fichier html à partir d'une liste de fichiers sur disques gen_list_html ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang="python"|code=
{{code|colNb=80|lang="python"|code=
def have_subdir( path ) :
#!/usr/bin/env python
     ok = 0
import re
     fs = os.listdir( path )
import os
     nb = len( fs )
def gen_list_html( path, file_pattern_txt ) :
     i = 0
     file_pattern = re.compile( file_pattern_txt )
     while (i < nb) and (ok==0) :
     fs = os.listdir(path)
         pathx = path + os.sep + fs[ i ]
     fs.sort()
         if os.path.isdir( pathx ) :
     print "<html><body><ol>"
             ok = 1
     for x in fs :
        i += 1
         file_path = path+os.sep+x
     return ok
         if os.path.isfile( file_path  ) :
             if file_pattern.match( x ) :
                print "<li><a href='%s'>%s</a></li>" %(x,x)
 
    print "</ol></body></html>"
if __name__ == '__main__' :
     gen_list_html( ".", ".*\.avi$" )
}}
}}
}}
}}


== Compte utilisateur ==
=== Générer une fichier html à partir d'une liste d'images/photo sur disques ===
=== get_username ===
{{parW|1=
<source lang="python">
{{code|colNb=80|lang="python"|code=
def get_username():
#!/usr/bin/python
    return getpass.getuser()
# -*- coding: UTF-8 -*-
</source>
import os, sys, re, codecs, time, shutil


=== get_hostname ===
<source lang="python">
def get_hostname():
    return socket.gethostbyaddr(socket.gethostname())[0]
</source>


=== get_homedir ===
srcPath = "."
<source lang="python">
fl = os.listdir(srcPath)
def get_homedir():
sorted(fl)
    homedir = os.path.expanduser('~')
    return homedir
</source>


== Réseau, Internet ==
f = codecs.open("index.html", "w", encoding = "UTF-8")
=== fromurl ===
<source lang="python">
def fromurl( cmd ) :
    encore = 1
    while encore :
        try :   
            f = urllib.urlopen( cmd )
            rep = f.read()
            f.close()
            encore = 0
        except Exception,e :
            #print str(e)
            encore = 1
           
    return rep
</source>
* [http://code.activestate.com/recipes/456195/ urrlib2 opener for SSL proxy (CONNECT method) (Python recipe)]
* [http://e1ven.com/2011/04/06/how-to-use-m2crypto-tutorial/ How to use m2crypto]


=== socket.setdefaulttimeout ===
f.write("<html style='background-color:#a0a0a0;margin:auto;'>\n")
<source lang="python">
    timeout = 10
    socket.setdefaulttimeout(timeout)
    text = urllib2.urlopen('http://at.bht.fr').read()
    print( text )
</source>


=== HTTPBasicAuthHandler ===
f.write("""<body
<source lang="python">
style='width:210mm;margin:auto;padding:5mm;background-color:#ffffff;'>
    auth_handler = urllib2.HTTPBasicAuthHandler()
<style type="text/css">
    auth_handler.add_password(
p.p {
                          realm='My Application',
width:180mm;background-color:#ffffff;margin:auto;
                          uri='',
}
                          user='',
td.g {
                          passwd=''
width:30mm; vertical-align:middle;
                          )
}
    opener = urllib2.build_opener( auth_handler )
td.d {
    # ...and install it globally so it can be used with urlopen.
width:150mm; vertical-align:top; background-color:#ffffff;font-size:10pt;
    urllib2.install_opener( opener )   
}
    text = urllib2.urlopen('https://at.bht.fr/DisEvtSim').read()
img{
    print( text )
width:28mm;
</source>
}
</style>
<p class="p">
<table align=center>
""")


=== ProxyBasicAuthHandler ===
for img in fl :
<source lang="python">
     name, ext = os.path.splitext(img)
     proxy_handler = urllib2.ProxyHandler({'http': 'http://proxypac.edf.fr:3128/','https': 'https://proxypac.edf.fr:3128/'})
     print(name.lower())
     proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
     if ext.lower() == ".jpg" :
     proxy_auth_handler.add_password('realm', 'proxypac.edf.fr', '', '')
        f.write("""\
     opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)  
<tr>
    # ...and install it globally so it can be used with urlopen.
    <td class='g'> <img src='%s'> </td>
    urllib2.install_opener(opener)   
     <td class='d'> TODO </td>
    text = urllib2.urlopen('http://at.bht.fr').read()
</tr>
    print( text )
""" % img)
</source>
 
f.write("""
</table>
</p>
</body>
""")
f.write("</html>\n")


=== ProxyBasicAuthHandler ===
f.close()
<source lang="python">
}}
    proxy_handler = urllib2.ProxyHandler({'http': 'http://proxypac.edf.fr:3128/','https': 'https://proxypac.edf.fr:3128/'})
}}
    proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
    proxy_auth_handler.add_password('realm', 'proxypac.edf.fr', '', '')
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='PDQ Application',
                          uri='https://at.bht.fr/DisEvtSim',
                          user='',
                          passwd='')
   
    opener = urllib2.build_opener(proxy_handler, proxy_auth_handler,auth_handler)   
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener(opener)   
    text = urllib2.urlopen('https://at.bht.fr/DisEvtSim').read()
    print( text )
</source>


=== https sans authentification ===
=== gen m3u8 - liste de mp3 - player list - utilisable par Rhythmbox ===
<source lang="python">
    timeout = 10
    socket.setdefaulttimeout(timeout)   
    text = urllib2.urlopen('https://www.google.fr').read()
    print( text )
</source>
 
== {{id|id_regex}}Expressions régulières ==
{{parW|1=
{{parW|1=
* voir plus généralement [[Expressions régulières]]
voir [https://atoross@at.bht.fr/svn/atTools/trunk/playList playList (svn atTools)]
}}
}}
=== Never match ===
<source lang="python">
class CNeverMatch :
    def match( self, f ) :
        return 0
</source>
=== Allways match ===
<source lang="python">
class CAllwaysMatch :
    def match( self, f ) :
        return 1
</source>


=== Remplacer avec sub : replace_re.py ===
=== genNewNames  ===
Un petit programme complet très utile pour traiter les fichiers (utilisation de {{m|sub}})
{{parW|1=
<source lang="python">
{{code|colNb=80|lang="python"|code=
#!/usr/bin/python
#!/usr/bin/python
# -*- coding: 'ISO8859-1' -*-
# -*- coding: UTF-8 -*-
import os, sys, re
import os, sys, re, random


def fromfile( filename ) :
def get_NewFileName( name, Index=1 ) :
     f = open(filename, "r")
     newname = name   
     text = f.read()
     name, ext = os.path.splitext( newname  )
     f.close()
     while os.path.exists( newname ) :       
     return text
        newname = name + ("%03d" % Index) + ext
        Index += 1
     return newname, Index


def replace_re( exp, remplacant, txt ) :
def genNewNames( path ) :
     pat=re.compile( exp )
     index=1
     newtxt= re.sub( pat, remplacant, txt)  
    fs = os.listdir(path)
    return newtxt
     nb = len(fs)
 
    num = 0
def replace_re_file( exp, remplacant, filename ) :
    while nb > 0 :
    txt = fromfile( filename )
        i = random.randint(0, nb-1 )
    return replace_re( exp, remplacant, txt )  
        nname = path+os.sep+fs[i]
 
        del fs[i]
def help() :
        if os.path.isfile( nname ) :
     print "HELP"
            nname0, ext = os.path.splitext(nname)
    print "\treplace_re.py expression_reguliere remplacant filename1 "
            pname, nname0 = os.path.split(nname)
 
            rname = pname + os.sep+"im%05d%s" % (num,ext)
if __name__ == '__main__' :     
            print "  ",nname, rname
     if len( sys.argv  ) == 4 :
            rname, index = get_NewFileName( rname, index )
        txt = replace_re_file( sys.argv[1], sys.argv[2], sys.argv[3] )
            os.rename( nname , rname )      
        print txt
        num += 1
    else :
        nb -= 1
        help()
       
</source>
def genNewNamesInSubDirs( path ) :  
     fs = os.listdir(path)
    for ff in fs :
        pathff = path+os.sep+ff
        print "[%s]" % pathff
        if os.path.isdir( pathff ) :
            genNewNames( pathff )
if __name__ == u'__main__' :     
     genNewNamesInSubDirs( "./Images/listes")  
    genNewNames( "./Images/listeAll" )
}}
}}
=== unix2dos ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/env python
###############
import sys


=== findall et sub ===
for fname in sys.argv[1:]:
Le code suivant remplace dans les lignes d'un fichier telles que
    infile = open( fname, "rb" )
    instr = infile.read()
    infile.close()
    outstr = instr.replace( "\r\n", "\n" ).replace( "\n\r", "\n" ).replace( "\r", "\n" ).replace( "\n", "\r\n" )


<source lang="xml">
    if len(outstr) == len(instr):
<td style="cursor:pointer; background-color: rgb(255, 255, 153); border: 1px solid #CCC;">&nbsp;</a></td>
        continue
</source>
   
    outfile = open( fname, "wb" )
    outfile.write( outstr )
    outfile.close()
}}
}}
=== clean_rep.py ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
import os
import re
pat_adir = re.compile( "\d{4}" )
pat_mdir = re.compile( "\d{4}-\d{2}" )
def clean_dirs() :
    """
    Delete empty directories with name like AAAA/AAAA-MM or AAAA.
    """
    adirs = os.listdir(".")
    for adir in adirs :
        if pat_adir.match( adir ) :
            mdirs = os.listdir(adir)
            for mdir in mdirs :
                if pat_mdir.match( mdir ) :
                    files = os.listdir( adir+os.sep+mdir )
                    if len(files)==0 :
                        os.rmdir( adir+os.sep+mdir )
            mdirs = os.listdir(adir)
            if len( mdirs )==0 :
                os.rmdir( adir )


toutes le chaines {{m|&amp;nbsp;}} par le calcul des couleurs qui se trouvent dans {{m|rgb(XXX, XXX, XXX)}}, cela donne dans notre cas :
if __name__ == '__main__' :
<source lang="xml">
     clean_dirs()
<td style="cursor:pointer; background-color: rgb(255, 255, 153); border: 1px solid #CCC;" >#ffff99</td>
</source>
 
<source lang="python">
def rgb( r,v,b ) :
    return "#%02x%02x%02x" %(r,v,b)
 
def dd( filename ) :
    pattern=re.compile(".*(rgb\(\d+, *\d+, *\d+\));.*")
    pat = re.compile( "&nbsp;" )
    txt = fromfile( filename ).split("\n")
    newtxt=""
    for l in txt :
        tr=re.findall( pattern, l)
        if len(tr)>0 :
            code=eval(tr[0])
            newl= re.sub( pat, code, l)
        else :
            newl=l
        print newl
        newtxt+=newl
</source>
 
== Les conversions ==
=== {{id|roundToSignificantDigitNumber}}Limiter le nombre de chiffres significatifs ===
{{parW|1=
{{code|lang=python|code=
def roundToSignificantDigitNumber( x , nbDigit ):
     if x != 0.0 :
        ten = round(math.log10(x))
        tenFac = 10 ** ten
        x = round(x / tenFac,  nbDigit-1)
        x = x * tenFac
    return x 
}}
}}
}}
}}
 
=== gen_rep.py ===
=== Convertir les None en nan ===
{{parW|1=
{{parW|1=
On utilise les liste en compréhension :
{{code|colNb=80|lang="python"|code=
{{code|lang=python|code=
#!/usr/bin/env python
a = ( None, 1.2, -4 )
# -*- coding: iso-8859-1 -*-
b = [ x  if x is not None else float("nan") for x in a ]
 
}}
import os
on obtient:
 
{{code|lang=text|code=
def gen_dirs() :
[nan, 1.2, -4]
    """
}}
    Generate directory with name like AAAA/AAAA-MM if it does not exist.
}}
    """
    for an in range(2000,2012) :
        dir_a = "%04d" %(an)
        if not os.path.exists( dir_a ) :
            os.mkdir( dir_a )
        for m in range(1,13) :
            dir_name = "%s%s%04d-%02d" %(dir_a,os.sep,an,m)
            print dir_name
            if not os.path.exists( dir_name ) :
                os.mkdir( dir_name )


=== hexadécimal ===
if __name__ == '__main__' :
{{parW|1=
     gen_dirs()
{{code|lang=python|code=
def hextoint( x ):
    return int(x,16)
def inttohex( x ):
     return hex(x)
}}
}}
}}
}}
=== binaire ===
=== size_on_system ===
{{parW|1=
{{parW|1=
{{code|lang=python|code=
{{code|colNb=80|lang="python"|code=
a= "{0:08b}".format( a )
def size_on_system( sf, sector_size ):
    if sector_size != None :
        s=0
        ns = sf % sector_size
        if ns == 0 :
            s = sf
        else :
            s = (sf / sector_size) * sector_size  + sector_size
    else :
      s=sf
    return s
}}
}}
ou
{{code|lang=python|code=
def bintoint( x ):
    return int(x,2)
def inttobin( x ):
    return bin(x)
}}
}}
 
=== size_of_dir ===
}}
 
=== Couleur vers int (alpha, red, green, blue) ===
{{parW|1=
{{parW|1=
{{code|lang=python|code=
{{code|colNb=80|lang="python"|code=
def argbToInt( a, r, g, b ):
def size_of_dir( path, sector_size=None  ):
     st=struct.pack(">BBBB", a, r, g, b )
     fs = os.listdir( path )
     i= struct.unpack(">I", st)[0]
     s=0
     return i
    for f in fs :
        pf = path+os.sep+f
        if os.path.isfile( pf ) :
            statinfo = os.stat( pf )
            s+= size_on_system( statinfo.st_size, sector_size )
        if os.path.isdir( pf ) :
            s+=size_of_dir( pf,sector_size  )
     return s
}}
}}
{{code|lang=python|code=
def intToArgb( i ):
    print i
    st=struct.pack(">I", i )
    return struct.unpack(">BBBB", st)
}}
}}
}}
=== sizeOfFile ===
 
== Formatage de texte ==
=== Le principe de la méthode {{mm|.format}} ===
{{parW|1=
{{parW|1=
Un exemple pour comprendre rapidement :
{{code|colNb=80|lang="python"|code=
{{code|lang=python|code=
def sizeOfFile( pathToFile ):
"{name1:1.2f} bla bla {name2:02d} {name1:f}".format(name1=3.14, name2=456)
    size = None
}}
    if os.path.isfile( pathToFile ) :
Ce qui produit :
        statinfo = os.stat( pathToFile )
{{code|lang=text|code=
        size = statinfo.st_size
'3.14 bla bla 456 3.140000'
    return size
}}
}}
=== have_subdir ===
{{parW|1=
{{code|colNb=80|lang="python"|code=
def have_subdir( path ) :
    ok = 0
    fs = os.listdir( path )
    nb = len( fs )
    i = 0
    while (i < nb) and (ok==0) :
        pathx = path + os.sep + fs[ i ]
        if os.path.isdir( pathx ) :
            ok = 1
        i += 1
    return ok
}}
}}
}}
}}


== Les dates ==
== Compte utilisateur ==
=== get_datetime_str ===
=== get_username ===
<source lang="python">
def get_datetime_str():
    return time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
</source>
 
<source lang="python">
<source lang="python">
def get_date_year( date ):
def get_username():
     return time.strftime("%Y",date)
     return getpass.getuser()
 
def get_date_month( date ):
    return time.strftime("%m",date)
 
def get_date_day( date ):
    return time.strftime("%d",date)
</source>
</source>


=== date_str2date_float ===
=== get_hostname ===
<source lang="python">
<source lang="python">
def date_str2float( sdate ):
def get_hostname():
     ds = time.strptime( sdate,"%d/%m/%Y"  )
     return socket.gethostbyaddr(socket.gethostname())[0]
    d = time.mktime( ds )
    return d
</source>
</source>


=== date_float2date_str ===
=== get_homedir ===
<source lang="python">
<source lang="python">
def date_float2date_str( d ):
def get_homedir():
     ds = time.strftime("%d/%m/%Y", time.gmtime(d) )
     homedir = os.path.expanduser('~')
     return ds
     return homedir
</source>
</source>


=== date_float_add_days ===
== Réseau, Internet ==
=== fromurl ===
<source lang="python">
<source lang="python">
def date_float_add_days( d, nb ):
def fromurl( cmd ) :
     nd = d + 3600*24*nb
     encore = 1
     return nd
    while encore :
        try :   
            f = urllib.urlopen( cmd )
            rep = f.read()
            f.close()
            encore = 0
        except Exception,e :
            #print str(e)
            encore = 1
           
    return rep
</source>
* [http://code.activestate.com/recipes/456195/ urrlib2 opener for SSL proxy (CONNECT method) (Python recipe)]
* [http://e1ven.com/2011/04/06/how-to-use-m2crypto-tutorial/ How to use m2crypto]
 
=== socket.setdefaulttimeout ===
<source lang="python">
    timeout = 10
     socket.setdefaulttimeout(timeout)
    text = urllib2.urlopen('http://at.bht.fr').read()
    print( text )
</source>
</source>
=== time2str str2time getAcTimeOfFile timeToFile fileToTime ===
{{parW|1=
{{code|colNb=70|lang=python|code=
timeForat = "%Y-%m-%d_%H-%M-%S"
def time2str( t=None ):
    st = time.localtime( t )
    return time.strftime( timeForat , st )
def str2time( text ) :
    st = time.strptime( dT, timeForat )
    return time.mktime( st )
def getAcTimeOfFile( filename ):
    infoStat = os.stat( filename )
    st = time.localtime( infoStat.st_atime )
    t = time.mktime( st )
    return t
def timeToFile( filename, t ):
    dT = time2str( t )
    tofile( filename, dT )
def fileToTime( filename ):
    dt = fromfile( filename )
}}
}}


== Physique ==
=== HTTPBasicAuthHandler ===
=== Nombre de chiffres significatifs  ===
<source lang="python">
{{parW|1=
    auth_handler = urllib2.HTTPBasicAuthHandler()
voir [[#roundToSignificantDigitNumber|Comment limiter le nombre de chiffres significatifs]].
    auth_handler.add_password(
}}
                          realm='My Application',
=== Rationnels et calculs symboliques / formels ===
                          uri='',
{{parW|1=
                          user='',
* [http://docs.sympy.org/latest/tutorial/intro.html#what-is-symbolic-computation What is Symbolic Computation?]
                          passwd=''
* [https://github.com/sympy/sympy/wiki/Number-Theory-in-SymPy Number Theory in SymPy]
                          )
* [https://github.com/sympy sympy]
    opener = urllib2.build_opener( auth_handler )
* [http://mpmath.org/ mpmath]
    # ...and install it globally so it can be used with urlopen.
* [http://mpmath.org/doc/current/ Welcome to mpmath’s documentation!]
    urllib2.install_opener( opener )   
{{code|colNb=70|lang=python|code=
    text = urllib2.urlopen('https://at.bht.fr/DisEvtSim').read()
from sympy import Rational
    print( text )
a = Rational(2,3)
</source>
print(a)
b = Rational(4,3)
print(a+b)


a=Rational(2*3*5*7*7,2*7*31)
=== ProxyBasicAuthHandler ===
print(a)
<source lang="python">
    proxy_handler = urllib2.ProxyHandler({'http': 'http://proxypac.edf.fr:3128/','https': 'https://proxypac.edf.fr:3128/'})
    proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
    proxy_auth_handler.add_password('realm', 'proxypac.edf.fr', '', '')
    opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)   
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener(opener)   
    text = urllib2.urlopen('http://at.bht.fr').read()
    print( text )
</source>


sympy.factorint(105)
=== ProxyBasicAuthHandler ===
a = 2*3*5*7*7
<source lang="python">
b= 2*7*31
    proxy_handler = urllib2.ProxyHandler({'http': 'http://proxypac.edf.fr:3128/','https': 'https://proxypac.edf.fr:3128/'})
sympy.factorint(a)
    proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
sympy.factorint(b)
    proxy_auth_handler.add_password('realm', 'proxypac.edf.fr', '', '')
pgcd = sympy.gcd(a,b)
    auth_handler = urllib2.HTTPBasicAuthHandler()
print(pgcd)
    auth_handler.add_password(realm='PDQ Application',
                          uri='https://at.bht.fr/DisEvtSim',
                          user='',
                          passwd='')
   
    opener = urllib2.build_opener(proxy_handler, proxy_auth_handler,auth_handler)  
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener(opener)   
    text = urllib2.urlopen('https://at.bht.fr/DisEvtSim').read()
    print( text )
</source>
 
=== https sans authentification ===
<source lang="python">
    timeout = 10
    socket.setdefaulttimeout(timeout)   
    text = urllib2.urlopen('https://www.google.fr').read()
    print( text )
</source>


aa= a / pgcd
== {{id|id_regex}}Expressions régulières ==
bb= b / pgcd
{{parW|1=
sympy.factorint(aa)
* voir plus généralement [[Expressions régulières]]
sympy.factorint(bb)
}}
}}
=== Never match ===
<source lang="python">
class CNeverMatch :
    def match( self, f ) :
        return 0
</source>
=== Allways match ===
<source lang="python">
class CAllwaysMatch :
    def match( self, f ) :
        return 1
</source>


{{code|colNb=70|lang=text|code=
=== Remplacer avec sub : replace_re.py ===
2/3
Un petit programme complet très utile pour traiter les fichiers (utilisation de {{m|sub}})
 
<source lang="python">
2
#!/usr/bin/python
 
# -*- coding: 'ISO8859-1' -*-
105
import os, sys, re
───
31
 
{3: 1, 5: 1, 7: 1}
{2: 1, 3: 1, 5: 1, 7: 2}
{2: 1, 7: 1, 31: 1}


14
def fromfile( filename ) :
    f = open(filename, "r")
    text = f.read()
    f.close()
    return text


{3: 1, 5: 1, 7: 1}
def replace_re( exp, remplacant, txt ) :
{31: 1}
    pat=re.compile( exp )
}}
    newtxt= re.sub( pat, remplacant, txt)
    return newtxt


{{code|colNb=70|lang=python|code=
def replace_re_file( exp, remplacant, filename ) :
from sympy import symbol
    txt = fromfile( filename )
from sympy import symbols
    return replace_re( exp, remplacant, txt )  
x = symbols("x")
 
sympy.init_printing(use_unicode=True)
def help() :
sympy.integrate(sympy.sin(x**2), x)
    print "HELP"
sympy.integrate(sympy.sin(x**2), (x,-sympy.oo,sympy.oo))
    print "\treplace_re.py expression_reguliere remplacant filename1 "
}}
{{code|colNb=70|lang=text|code=
Intégrale :


                ⎛√2⋅x⎞     
if __name__ == '__main__' :   
3⋅√2⋅√π⋅fresnels⎜────⎟⋅Γ(3/4)
    if len( sys.argv  ) == 4 :
                ⎝ √π ⎠     
        txt = replace_re_file( sys.argv[1], sys.argv[2], sys.argv[3] )
─────────────────────────────
        print txt
          8⋅Γ(7/4)         
    else :
        help()
</source>


√2⋅√π
=== findall et sub ===
─────
Le code suivant remplace dans les lignes d'un fichier telles que
  2 
}}
}}


=== Unités ===
<source lang="xml">
{{parW|1=
<td style="cursor:pointer; background-color: rgb(255, 255, 153); border: 1px solid #CCC;">&nbsp;</a></td>
* Voir [http://docs.sympy.org/latest/modules/physics/units/quantities.html]
</source>
{{code|colNb=70|lang=python|code=
from sympy.physics.units import *
a = 254 * m / s
b =  convert_to(a, [minute])
print(b)
find_unit(kg)
}}
{{code|colNb=70|lang=text|code=
15240*meter/minute


[g, kg, mg, ug, amu, mmu, amus, gram, mmus, grams, pound, pounds,
toutes le chaines {{m|&amp;nbsp;}} par le calcul des couleurs qui se trouvent dans {{m|rgb(XXX, XXX, XXX)}}, cela donne dans notre cas :
kilogram, kilograms, microgram, milligram, micrograms, milligrams,
<source lang="xml">
planck_mass, milli_mass_unit, atomic_mass_unit, atomic_mass_constant]
<td style="cursor:pointer; background-color: rgb(255, 255, 153); border: 1px solid #CCC;" >#ffff99</td>
}}
</source>
}}
==== Listes des unités ====
{{parW|1=
{{code|colNb=70|lang=python|code=
# Dimensionless


percent = percents = Rational(1, 100)
<source lang="python">
permille = permille = Rational(1, 1000)
def rgb( r,v,b ) :
    return "#%02x%02x%02x" %(r,v,b)


ten = Rational(10)
def dd( filename ) :
 
    pattern=re.compile(".*(rgb\(\d+, *\d+, *\d+\));.*")
yotta = ten**24
    pat = re.compile( "&nbsp;" )
zetta = ten**21
    txt = fromfile( filename ).split("\n")
exa = ten**18
    newtxt=""
peta = ten**15
    for l in txt :
tera = ten**12
        tr=re.findall( pattern, l)
giga = ten**9
        if len(tr)>0 :
mega = ten**6
            code=eval(tr[0])
kilo = ten**3
            newl= re.sub( pat, code, l)
deca = ten**1
        else :
deci = ten**-1
            newl=l
centi = ten**-2
        print newl
milli = ten**-3
        newtxt+=newl
micro = ten**-6
</source>
nano = ten**-9
pico = ten**-12
femto = ten**-15
atto = ten**-18
zepto = ten**-21
yocto = ten**-24


rad = radian = radians = 1
== Hashage ==
deg = degree = degrees = pi/180
=== crc32 : hashage de lignes de texte ou  de binaires ===
sr = steradian = steradians = 1
{{parW|1=
{{code|lang=python|code=
#!/usr/bin/python
#===============================================================================
# -*- coding: UTF-8 -*-
#===============================================================================
import binascii


# Base units
print("b:")
 
print( " ", b"hello" )
length = m = meter = meters = Unit('meter', 'm')
print( " ", "crc32: %0x" % binascii.crc32(b"hello") )  # bad way -> bytearray
mass = kg = kilogram = kilograms = Unit('kilogram', 'kg')
print("bytearray:")
time = s = second = seconds = Unit('second', 's')
print( " ", bytearray("hello", "utf8" ) )
current = A = ampere = amperes = Unit('ampere', 'A')
print( " ", "crc32: %0x" % binascii.crc32( bytearray("hello", "utf8" )))
temperature = K = kelvin = kelvins = Unit('kelvin', 'K')
print("b:")
amount = mol = mole = moles = Unit('mole', 'mol')
print( " ", b"barba-papa" )
luminosity = cd = candela = candelas = Unit('candela', 'cd')
print( " ", "crc32: %0x" % binascii.crc32 (b"barba-papa" ) )  # bad way -> bytearray
print("bytearray:")
print( " ", bytearray("barba-papa","utf8" ) )
print( " ", "crc32: %0x" % binascii.crc32(  bytearray("barba-papa", "utf8" ) ) )
print()
print( " ", bytearray("Installation on Linux (Obsolète)", "utf8" ) )
print( " ", "crc32: %0x" % binascii.crc32( bytearray("Installation on Linux (Obsolète)", "utf8" )))
}}
}}
== Les conversions ==
=== {{id|roundToSignificantDigitNumber}}Limiter le nombre de chiffres significatifs ===
{{parW|1=
{{code|lang=python|code=
def roundToSignificantDigitNumber( x , nbDigit ):
    if x != 0.0 :
        ten = round(math.log10(x))
        tenFac = 10 ** ten
        x = round(x / tenFac, nbDigit-1)
        x = x * tenFac
    return x 
}}
}}


=== Convertir les None en nan ===
{{parW|1=
On utilise les liste en compréhension :
{{code|lang=python|code=
a = ( None, 1.2, -4 )
b = [ x  if x is not None else float("nan") for x in a ]
}}
on obtient:
{{code|lang=text|code=
[nan, 1.2, -4]
}}
}}


# Derived units
=== hexadécimal ===
volume = meter**3
{{parW|1=
frequency = Hz = hz = hertz = 1/s
{{code|lang=python|code=
force = N = newton = newtons = m*kg/s**2
def hextoint( x ):
energy = J = joule = joules = N*m
    return int(x,16)
power = W = watt = watts = J/s
def inttohex( x ):
pressure = Pa = pa = pascal = pascals = N/m**2
    return hex(x)
charge = C = coulomb = coulombs = s*A
}}
voltage = v = V = volt = volts = W/A
}}
resistance = ohm = ohms = V/A
=== binaire ===
conductance = S = siemens = mho = mhos = A/V
{{parW|1=
capacitance = F = farad = farads = C/V
{{code|lang=python|code=
magnetic_flux = Wb = wb = weber = webers = J/A
a= "{0:08b}".format( a )
magnetic_flux_density = T = tesla = teslas = V*s/m**2
}}
inductance = H = henry = henrys = V*s/A
ou
speed = m/s
{{code|lang=python|code=
acceleration = m/s**2
def bintoint( x ):
density = kg/m**3
    return int(x,2)
optical_power = dioptre = D = 1/m
illuminance = lux = lx = sr*cd/m**2


# Common length units
def inttobin( x ):
    return bin(x)
}}


km = kilometer = kilometers = kilo*m
}}
dm = decimeter = decimeters = deci*m
cm = centimeter = centimeters = centi*m
mm = millimeter = millimeters = milli*m
um = micrometer = micrometers = micron = microns = micro*m
nm = nanometer = nanometers = nano*m
pm = picometer = picometers = pico*m


ft = foot = feet = Rational('0.3048')*m
=== Couleur vers int (alpha, red, green, blue) ===
inch = inches = Rational('25.4')*mm
{{parW|1=
yd = yard = yards = 3*ft
{{code|lang=python|code=
mi = mile = miles = 5280*ft
def argbToInt( a, r, g, b ):
    st=struct.pack(">BBBB", a, r, g, b )
    i= struct.unpack(">I", st)[0]
    return i
}}
{{code|lang=python|code=
def intToArgb( i ):
    print i
    st=struct.pack(">I", i )
    return struct.unpack(">BBBB", st)
}}
}}


== Formatage de texte ==
=== Le principe de la méthode {{mm|.format}} ===
{{parW|1=
Un exemple pour comprendre rapidement :
{{code|lang=python|code=
"{name1:1.2f} bla bla {name2:02d} {name1:f}".format(name1=3.14, name2=456)
}}
Ce qui produit :
{{code|lang=text|code=
'3.14 bla bla 456 3.140000'
}}
}}


# Common volume and area units
== Physique ==
 
=== Nombre de chiffres significatifs  ===
l = liter = liters = m**3 / 1000
{{parW|1=
dl = deciliter = deciliters = deci*l
voir [[#roundToSignificantDigitNumber|Comment limiter le nombre de chiffres significatifs]].
cl = centiliter = centiliters = centi*l
}}
ml = milliliter = milliliters = milli*l
=== Rationnels et calculs symboliques / formels ===
 
{{parW|1=
* [http://docs.sympy.org/latest/tutorial/intro.html#what-is-symbolic-computation What is Symbolic Computation?]
* [https://github.com/sympy/sympy/wiki/Number-Theory-in-SymPy Number Theory in SymPy]
* [https://github.com/sympy sympy]
* [http://mpmath.org/ mpmath]
* [http://mpmath.org/doc/current/ Welcome to mpmath’s documentation!]
{{code|colNb=70|lang=python|code=
from sympy import Rational
a = Rational(2,3)
print(a)
b = Rational(4,3)
print(a+b)


# Common time units
a=Rational(2*3*5*7*7,2*7*31)
print(a)


ms = millisecond = milliseconds = milli*s
sympy.factorint(105)
us = microsecond = microseconds = micro*s
a = 2*3*5*7*7
ns = nanosecond = nanoseconds = nano*s
b= 2*7*31
ps = picosecond = picoseconds = pico*s
sympy.factorint(a)
sympy.factorint(b)
pgcd = sympy.gcd(a,b)
print(pgcd)


minute = minutes = 60*s
aa= a / pgcd
h = hour = hours = 60*minute
bb= b / pgcd
day = days = 24*hour
sympy.factorint(aa)
sympy.factorint(bb)
}}


anomalistic_year = anomalistic_years = Rational('365.259636')*day
{{code|colNb=70|lang=text|code=
sidereal_year = sidereal_years = Rational('31558149.540')*s
2/3
tropical_year = tropical_years = Rational('365.24219')*day
common_year = common_years = Rational('365')*day
julian_year = julian_years = Rational('365.25')*day
draconic_year = draconic_years = Rational('346.62')*day
gaussian_year = gaussian_years = Rational('365.2568983')*day
full_moon_cycle = full_moon_cycles = Rational('411.78443029')*day


year = years = tropical_year
2


105
───
31


# Common mass units
{3: 1, 5: 1, 7: 1}
{2: 1, 3: 1, 5: 1, 7: 2}
{2: 1, 7: 1, 31: 1}


g = gram = grams = kilogram / kilo
14
mg = milligram = milligrams = milli * g
ug = microgram = micrograms = micro * g


{3: 1, 5: 1, 7: 1}
{31: 1}
}}


#----------------------------------------------------------------------------
{{code|colNb=70|lang=python|code=
# Physical constants
from sympy import symbol
#
from sympy import symbols
c = speed_of_light = 299792458 * m/s
x = symbols("x")
G = gravitational_constant = Rational('6.67428') * ten**-11 * m**3 / kg / s**2
sympy.init_printing(use_unicode=True)
u0 = magnetic_constant = 4*pi * ten**-7 * N/A**2
sympy.integrate(sympy.sin(x**2), x)
e0 = electric_constant = 1/(u0 * c**2)
sympy.integrate(sympy.sin(x**2), (x,-sympy.oo,sympy.oo))
Z0 = vacuum_impedance = u0 * c
}}
 
{{code|colNb=70|lang=text|code=
planck = Rational('6.62606896') * ten**-34 * J*s
Intégrale :
hbar = planck / (2*pi)


avogadro_number = Rational('6.02214179') * 10**23
                ⎛√2⋅x⎞     
avogadro = avogadro_constant = avogadro_number / mol
3⋅√2⋅√π⋅fresnels⎜────⎟⋅Γ(3/4)
boltzmann = Rational('1.3806505') * ten**-23 * J / K
                ⎝ √π ⎠     
─────────────────────────────
          8⋅Γ(7/4)        


gee = gees = Rational('9.80665') * m/s**2
√2⋅√π
atmosphere = atmospheres = atm = 101325 * pascal
─────
  2
}}
}}


kPa = kilo*Pa
=== Unités ===
bar = bars = 100*kPa
{{parW|1=
pound = pounds = 0.45359237 * kg * gee  # exact
* Voir [http://docs.sympy.org/latest/modules/physics/units/quantities.html]
psi = pound / inch ** 2
{{code|colNb=70|lang=python|code=
dHg0 = 13.5951  # approx value at 0 C
from sympy.physics.units import *
mmHg = dHg0 * 9.80665 * Pa
a = 254 * m / s
amu = amus = gram / avogadro / mol
b = convert_to(a, [minute])
mmu = mmus = gram / mol
print(b)
quart = quarts = Rational(231, 4) * inch**3
find_unit(kg)
eV = 1.602176487e-19 * J
}}
{{code|colNb=70|lang=text|code=
15240*meter/minute


# Other convenient units and magnitudes
[g, kg, mg, ug, amu, mmu, amus, gram, mmus, grams, pound, pounds,
 
kilogram, kilograms, microgram, milligram, micrograms, milligrams,
ly = lightyear = lightyears = c*julian_year
planck_mass, milli_mass_unit, atomic_mass_unit, atomic_mass_constant]
au = astronomical_unit = astronomical_units = 149597870691*m
}}
}}
}}
}}
 
==== Listes des unités ====
== Math ==
=== Équation de second degré  ===
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|colNb=70|lang=python|code=
def secondDegreeEquation(a,b,c):
# Dimensionless
    # a*x*x + b*y + c = 0
 
    x1 = None
percent = percents = Rational(1, 100)
    x2 = None
permille = permille = Rational(1, 1000)
    det = b*b - 4 * a * c
    if det>= 0.0 :
        sqDet = math.sqrt(det)
        a2 = a * 2.0
        x1 = (-b - sqDet ) / a2
        x2 = (-b + sqDet ) / a2
    return x1, x2
}}
}}
=== Régression linéaire  ===
{{parW|1=
source [https://www.science-emergence.com/Articles/R%C3%A9gression-lin%C3%A9aire-simple-avec-python/ www.science-emergence.com]
{{figc|Régression linéaire|linearRegressionInPython.png}}
{{code|colNb=70|lang=python|code=
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt


x,y = np.loadtxt("test.txt", unpack='true')
ten = Rational(10)


plt.scatter(x,y)
yotta = ten**24
 
zetta = ten**21
regr = linear_model.LinearRegression()
exa = ten**18
regr.fit(x[:,np.newaxis], y)
peta = ten**15
 
tera = ten**12
x_test = np.linspace(np.min(x), np.max(x), 100)
giga = ten**9
 
mega = ten**6
plt.plot(x_test, regr.predict(x_test[:,np.newaxis]), color='blue', linewidth=3)
kilo = ten**3
deca = ten**1
deci = ten**-1
centi = ten**-2
milli = ten**-3
micro = ten**-6
nano = ten**-9
pico = ten**-12
femto = ten**-15
atto = ten**-18
zepto = ten**-21
yocto = ten**-24
 
rad = radian = radians = 1
deg = degree = degrees = pi/180
sr = steradian = steradians = 1


plt.show()
# Base units
}}
Pour obtenir le coefficient directeur et l'ordonnée à l'origine de la droite:
{{code|colNb=70|lang=python|code=
print 'slope', regr.coef_
print 'intercept', regr.intercept_
}}
donne ici
{{code|colNb=70|lang=python|code=
slope [ 0.80723367]
intercept -0.623011727604
}}
}}


=== Décomposition d'un nombre en facteurs premiers ===
length = m = meter = meters = Unit('meter', 'm')
{{parW|1=
mass = kg = kilogram = kilograms = Unit('kilogram', 'kg')
{{code|colNb=70|lang=python|code=
time = s = second = seconds = Unit('second', 's')
#!/usr/bin/python
current = A = ampere = amperes = Unit('ampere', 'A')
# -*- coding: utf-8 -*-
temperature = K = kelvin = kelvins = Unit('kelvin', 'K')
amount = mol = mole = moles = Unit('mole', 'mol')
def facteurs(n):
luminosity = cd = candela = candelas = Unit('candela', 'cd')
    """facteurs(n): décomposition d'un nombre entier n en facteurs premiers"""
 
    F = []
 
    if n==1:
# Derived units
        return F
volume = meter**3
    # recherche de tous les facteurs 2 s'il y en a
frequency = Hz = hz = hertz = 1/s
    while n>=2:
force = N = newton = newtons = m*kg/s**2
        x,r = divmod(n,2)
energy = J = joule = joules = N*m
        if r!=0:
power = W = watt = watts = J/s
            break
pressure = Pa = pa = pascal = pascals = N/m**2
        F.append(2)
charge = C = coulomb = coulombs = s*A
        n = x
voltage = v = V = volt = volts = W/A
    # recherche des facteurs 1er >2
resistance = ohm = ohms = V/A
    i=3
conductance = S = siemens = mho = mhos = A/V
    rn = lsqrt(n)+1
capacitance = F = farad = farads = C/V
    while i<=n:
magnetic_flux = Wb = wb = weber = webers = J/A
        if i>rn:
magnetic_flux_density = T = tesla = teslas = V*s/m**2
            F.append(n)
inductance = H = henry = henrys = V*s/A
            break
speed = m/s
        x,r = divmod(n,i)
acceleration = m/s**2
        if r==0:
density = kg/m**3
            F.append(i)
optical_power = dioptre = D = 1/m
            n=x
illuminance = lux = lx = sr*cd/m**2
            rn = lsqrt(n)+1
        else:
            i += 2
    return F
# exemple d'utilisation:
print facteurs(100)  # affiche [2,2,5,5]
print facteurs(123456789)  # affiche [3,3,3607,3803]
print facteurs(12345678901234567890) # affiche [2,3,3,5,101,3541,3607,3803,27961L]
# et test avec un nombre premier
print facteurs(4291979)  # affiche [4291979]
}}
source: http://python.jpvweb.com/python/mesrecettespython/doku.php?id=decomposition_en_facteurs_premiers
}}
=== Histogram - densité de probabilité ===
==== Numpy ====
{{parW|1=
Utilisation la fonction d’histogramme de numpy  voir [https://numpy.org/doc/stable/reference/generated/numpy.histogram.html]


Avec l’option {{mm|density = True}} :
# Common length units


Soit n Intervalles I(i) de longueur L(i)  
km = kilometer = kilometers = kilo*m
et Q(i) la quantité de valeurs incluse dans I(i)
dm = decimeter = decimeters = deci*m
cm = centimeter = centimeters = centi*m
mm = millimeter = millimeters = milli*m
um = micrometer = micrometers = micron = microns = micro*m
nm = nanometer = nanometers = nano*m
pm = picometer = picometers = pico*m
 
ft = foot = feet = Rational('0.3048')*m
inch = inches = Rational('25.4')*mm
yd = yard = yards = 3*ft
mi = mile = miles = 5280*ft
 
 
# Common volume and area units


Soit Qt = somme des Qi
l = liter = liters = m**3 / 1000
dl = deciliter = deciliters = deci*l
cl = centiliter = centiliters = centi*l
ml = milliliter = milliliters = milli*l


Alors l’histogramme avec density=True est la suite des H(i) = Q(i)/L(i)/Qt


Et ainsi l’intégrale de de l’histogramme vaut 1 car c’est la somme de  des H(i)*L(i) =  somme de Q(i)/Qt = 1
# Common time units


Voici un petit code python pour illustrer :
ms = millisecond = milliseconds = milli*s
us = microsecond = microseconds = micro*s
ns = nanosecond = nanoseconds = nano*s
ps = picosecond = picoseconds = pico*s


{{code|colNb=80|lang=python|code=
minute = minutes = 60*s
#!/usr/bin/python
h = hour = hours = 60*minute
# -*- coding: UTF-8 -*-
day = days = 24*hour
import numpy as np
interval = np.linspace(-0.5,1.5,20)
print(interval)
intervalD = np.diff(interval)
print(intervalD)
vals = [ -0.2, 0.1, 0.4, -0.8, 2.8, 0.4 , 6.8, 1.3  ]
hist0 = np.histogram( vals, bins=interval )
hist = np.histogram(  vals, bins=interval , density=True)
print("quantity")
print(hist0[0].tolist())
print("density")
print(hist[0].tolist())
print("integral")
print( np.sum(hist[0]*intervalD)  )
}}
ce qui donne :
{{code|colNb=80|lang=text|code=
[-0.5        -0.39473684 -0.28947368 -0.18421053 -0.07894737  0.02631579
  0.13157895  0.23684211  0.34210526  0.44736842  0.55263158  0.65789474
  0.76315789  0.86842105  0.97368421  1.07894737  1.18421053  1.28947368
  1.39473684  1.5      ]
[0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316]
quantity
[0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
density
[0.0, 0.0, 1.9, 0.0, 0.0, 1.9, 0.0, 0.0, 3.8, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.8999999999999981, 0.0]
integral
1.0
}}
}}


== Parallélisme  ==
anomalistic_year = anomalistic_years = Rational('365.259636')*day
=== multiprocessing ===
sidereal_year = sidereal_years = Rational('31558149.540')*s
{{parW|1=
tropical_year = tropical_years = Rational('365.24219')*day
{{code|colNb=70|lang=python|code=
common_year = common_years = Rational('365')*day
#!/usr/bin/python
julian_year = julian_years = Rational('365.25')*day
# -*- coding: UTF-8 -*-
draconic_year = draconic_years = Rational('346.62')*day
#***********************************************************
gaussian_year = gaussian_years = Rational('365.2568983')*day
full_moon_cycle = full_moon_cycles = Rational('411.78443029')*day


import time
year = years = tropical_year
import math
import sys
from multiprocessing import Pool


def parallel_call(params):  # a helper for calling 'remote' instances
    cls = getattr(sys.modules[__name__], params[0])  # get our class type
    instance = cls.__new__(cls)  # create a new instance without invoking __init__
    instance.__dict__ = params[1]  # apply the passed state to the new instance
    method = getattr(instance, params[2])  # get the requested method
    args = params[3] if isinstance(params[3], (list, tuple)) else [params[3]]
    return method(*args)  # expand arguments, call our method and return the result


class A(object):
# Common mass units
    def __init__(self, num):
 
        self.num = num
g = gram = grams = kilogram / kilo
        self.z = None
mg = milligram = milligrams = milli * g
        self.procNb = 6
ug = microgram = micrograms = micro * g


    def calc(self, fc, num):
        self.z = 0
        self.num = num
        for x in range(7000000) :
                y = math.cos(x*x)
                self.z = math.sqrt(abs(y)) + fc
       
        return (self.num, self.z, self)


    def run(self, fcNum):
#----------------------------------------------------------------------------
        t = Pool(processes=self.procNb)
# Physical constants
        rs = t.map(parallel_call, self.prepare_call("calc", (fcNum) ))
#
        t.close()
c = speed_of_light = 299792458 * m/s
        return rs
G = gravitational_constant = Rational('6.67428') * ten**-11 * m**3 / kg / s**2
u0 = magnetic_constant = 4*pi * ten**-7 * N/A**2
e0 = electric_constant = 1/(u0 * c**2)
Z0 = vacuum_impedance = u0 * c


    def prepare_call(self, name, args):  # creates a 'remote call' package for each argument
planck = Rational('6.62606896') * ten**-34 * J*s
        for arg in args:
hbar = planck / (2*pi)
            yield [self.__class__.__name__, self.__dict__, name, arg]


if __name__ == "__main__":  # important protection for cross-platform use
avogadro_number = Rational('6.02214179') * 10**23
    data = [
avogadro = avogadro_constant = avogadro_number / mol
            (0.1,1),
boltzmann = Rational('1.3806505') * ten**-23 * J / K
            (0.2,2),
 
            (0.5,3),
gee = gees = Rational('9.80665') * m/s**2
            (0.6,4),
atmosphere = atmospheres = atm = 101325 * pascal
            (0.71,5),
 
            (2.45,6),
kPa = kilo*Pa
            (2.5,7),
bar = bars = 100*kPa
            (9.45,8),
pound = pounds = 0.45359237 * kg * gee  # exact
            (11.05,9),
psi = pound / inch ** 2
            (0.45,10)                       
dHg0 = 13.5951 # approx value at 0 C
            ]
mmHg = dHg0 * 9.80665 * Pa
   
amu = amus = gram / avogadro / mol
    t0 = time.time()
mmu = mmus = gram / mol
    # parallel
quart = quarts = Rational(231, 4) * inch**3
    print("\nparallèle")
eV = 1.602176487e-19 * J
    aa = A(2)
 
    res = aa.run( data )
# Other convenient units and magnitudes
    for num, z, a in res :
 
        print("% 5d % 5.1f % 5d % 5d" % (num, z, a.num, id(a)))
ly = lightyear = lightyears = c*julian_year
               
au = astronomical_unit = astronomical_units = 149597870691*m
    pt = time.time()-t0         
    print("\n t=% 5.1f" % (pt),"s" )
    t0 = time.time()
       
    # serial
    print("\nsérie")
    for fc, num in data :
        num, z, a = aa.calc(fc, num)
        print("% 5d % 5.1f % 5d % 5d" % (num, z, a.num, id(aa)))
       
    st = time.time()-t0 
    print("\n t=% 5.1f" % (st),"s" )
    print("\n gain=% 5.1f % 5.1f" % (st/pt, st/a.procNb),"" )
}}
}}
}}
}}
=== Timer (onsolète voir multiprocessing) ===
 
== Math ==
=== Équation de second degré  ===
{{parW|1=
{{parW|1=
{{code|colNb=70|lang=python|code=
{{code|colNb=70|lang=python|code=
import threading
def secondDegreeEquation(a,b,c):
prLock = threading.RLock()
    # a*x*x + b*y + c = 0
# ...
    x1 = None
         # initialization
    x2 = None
         self.timer = None
    det = b*b - 4 * a * c
        self.executing = False
    if det>= 0.0 :
        self.wating = False
        sqDet = math.sqrt(det)
# ...
        a2 = a * 2.0
    ############################################################################
         x1 = (-b - sqDet ) / a2
    def doSomeThing(self):
         x2 = (-b + sqDet ) / a2
        global prLock
    return x1, x2
        prLock.acquire()
}}
        if self.executing:
}}
=== Régression linéaire  ===
{{parW|1=
source [https://www.science-emergence.com/Articles/R%C3%A9gression-lin%C3%A9aire-simple-avec-python/ www.science-emergence.com]
{{figc|Régression linéaire|linearRegressionInPython.png}}
{{code|colNb=70|lang=python|code=
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt
 
x,y = np.loadtxt("test.txt", unpack='true')


            # ... do someThing in parallel thread
plt.scatter(x,y)


        prLock.release()
regr = linear_model.LinearRegression()
        self.launchTimer()
regr.fit(x[:,np.newaxis], y)
    ############################################################################
    def launchTimer(self):
        global prLock
        if self.executing:
            self.timer = threading.Timer(10, self.doSomeThing)
            self.timer.start()
        else:
            prLock.acquire()
            self.wating = False
            prLock.release()
# ...
    # start the main process
    prLock.acquire()
    param.wating = True
    param.executing = True
    prLock.release()


    # ... do things in the main thread
x_test = np.linspace(np.min(x), np.max(x), 100)


    prLock.acquire()
plt.plot(x_test, regr.predict(x_test[:,np.newaxis]), color='blue', linewidth=3)
    param.executing = False


    print "wait ..."
plt.show()
    prLock.release()
}}
 
Pour obtenir le coefficient directeur et l'ordonnée à l'origine de la droite:
    waiting = True
{{code|colNb=70|lang=python|code=
    while waiting:
print 'slope', regr.coef_
        prLock.acquire()
print 'intercept', regr.intercept_
        waiting = param.wating
}}
        prLock.release()
donne ici
    # the end of all
{{code|colNb=70|lang=python|code=
}}
slope [ 0.80723367]
intercept -0.623011727604
}}
}}
}}


== Aller plus loin avec le langage ==
=== Décomposition d'un nombre en facteurs premiers ===
 
=== Obtenir le nom ou les noms de la variable ===
 
{{Todo|texte=A tester et valider :}}
<source lang="python">
def find_names(obj):
    frame = sys._getframe()
    for frame in iter(lambda: frame.f_back, None):
        frame.f_locals
    result = []
    for referrer in gc.get_referrers(obj):
        if isinstance(referrer, dict):
            for k, v in referrer.iteritems():
                if v is obj:
                    result.append(k)
    return result
</source>
 
=== Obtenir le nom de la fonction ===
 
==== Nom de fichier,  n° de ligne, nom de fonction sur plusieurs niveaux ====
{{parW|1=
{{parW|1=
{{code|lang=python|code=
{{code|colNb=70|lang=python|code=
import sys
#!/usr/bin/python
import inspect
# -*- coding: utf-8 -*-
 
def getFrameStr( fr  ):
    _, fileName = os.path.split( fr.f_code.co_filename )
    fname = fr.f_code.co_name
    line = fr.f_lineno
    return "%s(%d).%s" % (fileName,line,  fname)
   
   
def pfname():
def facteurs(n):
     src1 = ""
     """facteurs(n): décomposition d'un nombre entier n en facteurs premiers"""
    src2 = ""
     F = []
     src3 = ""   
     if n==1:
     nb = len(inspect.stack())
        return F
     print( nb )
     # recherche de tous les facteurs 2 s'il y en a
     if nb > 2 :
     while n>=2:
         src1 = getFrameStr( sys._getframe(3) )
         x,r = divmod(n,2)
    if nb > 1 :  
        if r!=0:
         src2 = getFrameStr( sys._getframe(2) )
            break
     if nb > 0 :  
         F.append(2)
         src3 = getFrameStr( sys._getframe(1) )  
        n = x
     print( "%s %s %s : " %(src1,src2,src3), end="" )
    # recherche des facteurs 1er >2
 
    i=3
}}
    rn = lsqrt(n)+1
     while i<=n:
        if i>rn:
            F.append(n)
            break
         x,r = divmod(n,i)
        if r==0:
            F.append(i)
            n=x
            rn = lsqrt(n)+1
        else:
            i += 2
     return F
# exemple d'utilisation:
print facteurs(100)  # affiche [2,2,5,5]
print facteurs(123456789)  # affiche [3,3,3607,3803]
print facteurs(12345678901234567890) # affiche [2,3,3,5,101,3541,3607,3803,27961L]
# et test avec un nombre premier
print facteurs(4291979)  # affiche [4291979]
}}
}}
==== Fonction courante ====
source: http://python.jpvweb.com/python/mesrecettespython/doku.php?id=decomposition_en_facteurs_premiers
<source lang="python">
}}
def pfname( self ):
=== Histogram - densité de probabilité ===
    print self.__class__.__name__,sys._getframe().f_code.co_name
==== Numpy ====
</source>
{{parW|1=
Utilisation la fonction d’histogramme de numpy  voir [https://numpy.org/doc/stable/reference/generated/numpy.histogram.html]


<source lang="python">
Avec l’option {{mm|density = True}} :
def func_name():
    return sys._getframe(1).f_code.co_name
</source>


==== Fonction appelante ====
Soit n Intervalles I(i) de longueur L(i)
<source lang="python">
et Q(i) la quantité de valeurs incluse dans I(i)
def pfname( self ):
    print self.__class__.__name__,sys._getframe(1).f_code.co_name
</source>


Voir aussi [[#error_in_function|error_in_function]]
Soit Qt = somme des Qi


Alors l’histogramme avec density=True est la suite des H(i) = Q(i)/L(i)/Qt


Et ainsi l’intégrale de de l’histogramme vaut 1 car c’est la somme de  des H(i)*L(i) =  somme de Q(i)/Qt = 1


==== Liens ====
Voici un petit code python pour illustrer :  
*[http://code.activestate.com/recipes/66062/ www.activestate.com (Recipe 66062: Determining Current Function Name) ]


== utilisation des feuilles excel ==
{{code|colNb=80|lang=python|code=
{{parW|1=
#!/usr/bin/python
* Lien vers les modules (source) :
# -*- coding: UTF-8 -*-
*: http://www.python-excel.org/
import numpy as np
}}{{parW|1=
interval = np.linspace(-0.5,1.5,20)
Working with Excel Files in Python
print(interval)
This site contains pointers to the best information available about working with Excel files in the Python programming language.
intervalD = np.diff(interval)
}}{{parW|1=
print(intervalD)
The Packages
vals = [ -0.2, 0.1, 0.4, -0.8, 2.8, 0.4 , 6.8, 1.3  ]
There are python packages available to work with Excel files that will run on any Python platform and that do not require either Windows or Excel to be used. They are fast, reliable and open source:
hist0 = np.histogram( vals, bins=interval )
 
hist = np.histogram(  vals, bins=interval , density=True)
Download | Documentation | Bitbucket
print("quantity")
print(hist0[0].tolist())
print("density")
print(hist[0].tolist())
print("integral")
print( np.sum(hist[0]*intervalD)  )
}}
ce qui donne :
{{code|colNb=80|lang=text|code=
[-0.5        -0.39473684 -0.28947368 -0.18421053 -0.07894737  0.02631579
  0.13157895  0.23684211  0.34210526  0.44736842  0.55263158  0.65789474
  0.76315789  0.86842105  0.97368421  1.07894737  1.18421053  1.28947368
  1.39473684  1.5      ]
[0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316]
quantity
[0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
density
[0.0, 0.0, 1.9, 0.0, 0.0, 1.9, 0.0, 0.0, 3.8, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.8999999999999981, 0.0]
integral
1.0
}}
}}


* openpyxl
== Parallélisme  ==
*: The recommended package for reading and writing Excel 2010 files (ie: .xlsx)
=== multiprocessing ===
*: Download https://pypi.python.org/pypi/openpyxl
{{parW|1=
*: Documentation https://openpyxl.readthedocs.io/en/default/
{{code|lang=python|code=
*: Bitbucket https://bitbucket.org/openpyxl/openpyxl
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#***********************************************************


* xlsxwriter
import time
* An alternative package for writing data, formatting information and, in particular, charts in the Excel 2010 format (ie: .xlsx)
import math
*: Download
import sys
*: Documentation
from multiprocessing import Pool
*: Bitbucket


* xlrd
def getPoreccessorNumber():
*: This package is for reading data and formatting information from older Excel files (ie: .xls)
    return multiprocessing.cpu_count()
*:


* xlwt
def parallelCall(params): # a helper for calling 'remote' instances
*: This package is for writing data and formatting information to older Excel files (ie: .xls)
   
*:
    # get our class type
    cls = getattr(sys.modules[__name__], params[0]) 
   
    # create a new instance without invoking __init__
    instance = cls.__new__(cls) 
   
    # apply the passed state to the new instance
    instance.__dict__ = params[1] 
   
    # get the requested method
    method = getattr(instance, params[2]) 
    args = params[3] if isinstance(params[3], (list, tuple)) else [params[3]]
   
    # expand arguments, call our method and return the result
    return method(*args) 


* xlutils
class CMultiProc(object):
*: This package collects utilities that require both xlrd and xlwt, including the ability to copy and modify or filter existing excel files.  
    def __init__(self):
*: NB: In general, these use cases are now covered by openpyxl!
        self.val = None


}}
    def calc(self, num,  i1, i2):
        self.num = num       
        val = 0       
        for i in range(i1, i2) :
                #val += math.cos(math.sqrt(i*i))
                val += i*i
        self.val = val
        return ( self.num, val )


== clipboard - presse-papier ==
    def do(self, data):
=== le module clipboard ===
        t = Pool(processes=len(data))
{{parW|1=
        rs = t.map(parallelCall, self.prepareCall("calc", (data) ))
{{code|lang=python|code=
        t.close()
import clipboard
        return rs


clipboard.copy("abc"# now the clipboard content will be string "abc"
    # creates a 'remote call' package for each argument
    def prepareCall(self, name, args):  
        for arg in args:
            yield [self.__class__.__name__, self.__dict__, name, arg]


text = clipboard.paste()  # text will have the content of clipboard
if __name__ == "__main__":  # important protection for cross-platform use
   
    ############################################################################
    data = [
            (1,0      ,10000000),
            (2,10000000,20000000),
            (3,20000000,30000000),
            (4,30000000,40000000),
            (5,40000000,50000000),
            (6,50000000,60000000),
            (7,60000000,70000000),
            (8,70000000,80000000),
            (9,80000000,90000000),
            (10,90000000,100000000),
            (11,100000000,110000000),
            (12,110000000,120000000),
            (13,120000000,130000000),
            (14,130000000,140000000),
            (15,140000000,150000000),
            (16,150000000,160000000), 
            ]
    ############################################################################
    # parallel   
    print("parallèle")
    t0 = time.time()
    multiProc = CMultiProc(  )   
    res =  multiProc.do( data )
    vp = 0
    for num, val in res :
        vp += val
        print("% 5d % 5.1f " % (num, val) )
    print(vp)               
    pt = time.time()-t0         
    print("t=% 5.1f" % (pt),"s" )
    ############################################################################   
    # serial
    print("série")
    t0 = time.time()
    vs = 0
    for i in range(0,160000000) :
        # v += math.cos((math.sqrt(i*i)) )
        vs += i*i
    st = time.time()-t0
    print(vs)   
    print("t=% 5.1f" % (st),"s" )
    ############################################################################   
    # diff
    print("Diff", vp -vs )
    print("Gain", st / pt  )
}}
Résultats:
{{code|lang=text|code=
parallèle
    1  333333283333335023616.0
    2  2333333183333335040000.0
    3  6333333083333335187456.0
    4  12333332983333334810624.0
    5  20333332883333336530944.0
    6  30333332783333336154112.0
    7  42333332683333335777280.0
    8  56333332583333331206144.0
    9  72333332483333330829312.0
  10  90333332383333334646784.0
  11  110333332283333334269952.0
  12  132333332183333329698816.0
  13  156333332083333337710592.0
  14  182333331983333341528064.0
  15  210333331883333324374016.0
  16  240333331783333319802880.0
1365333320533333360000000
t=  1.9 s
série
1365333320533333360000000
t= 12.0 s
Diff 0
Gain 6.214744302379906
}}
}}
source  : https://pypi.python.org/pypi/clipboard/0.0.4
il faut aussi : https://pypi.python.org/pypi/pyperclip
}}
}}
=== Exemple d'application : copier le chemin du fond d'écran de gnome dans le clipboard  ===
 
=== Timer (onsolète voir multiprocessing) ===
{{parW|1=
{{parW|1=
{{code|colNb=80|lang=python|code=
import threading
prLock = threading.RLock()
# ...
        # initialization
        self.timer = None
        self.executing = False
        self.wating = False
# ...
    ############################################################################
    def doSomeThing(self):
        global prLock
        prLock.acquire()
        if self.executing:


{{code|lang=bash|code=
            # ... do someThing in parallel thread
#!/bin/bash
the_bash_file=$0
the_bash_file_dir_name=$(realpath `dirname "$the_bash_file"`)
the_bash_file_base_name=`basename "$the_bash_file"`


imgpath=$(gsettings get org.gnome.desktop.background picture-uri)
        prLock.release()
        self.launchTimer()
    ############################################################################
    def launchTimer(self):
        global prLock
        if self.executing:
            self.timer = threading.Timer(10, self.doSomeThing)
            self.timer.start()
        else:
            prLock.acquire()
            self.wating = False
            prLock.release()
# ...
    # start the main process
    prLock.acquire()
    param.wating = True
    param.executing = True
    prLock.release()


python ${the_bash_file_dir_name}/toClipBoard.py "${imgpath}"
    # ... do things in the main thread
}}


{{code|lang=python|code=
    prLock.acquire()
#!/bin/python
    param.executing = False
import os
import sys
import clipboard
clipboard.copy(sys.argv[1][1:-1])  
}}
}}


== Texte ==
    print "wait ..."
=== Supprimer les accents ===
    prLock.release()
<source lang="python">
import unicodedata


def strip_accents(ss):
    waiting = True
  s=ss
    while waiting:
  return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')
        prLock.acquire()
</source>
        waiting = param.wating
        prLock.release()
    # the end of all
}}
}}
 
== Aller plus loin avec le langage ==
 
=== Obtenir le nom ou les noms de la variable ===


=== rearrange_text ===
{{Todo|texte=A tester et valider :}}
<source lang="python">
<source lang="python">
patWordSep=re.compile("\s+", re.DOTALL )
def find_names(obj):
def rearrange_text( text, tab, rearrange_lf=0 ):
     frame = sys._getframe()
     lines = list()
     for frame in iter(lambda: frame.f_back, None):
     if rearrange_lf :
         frame.f_locals
        txt = ''
    result = []
        ww = text.split('\n')
    for referrer in gc.get_referrers(obj):
         if len(ww) == 0 :
         if isinstance(referrer, dict):
            txt = text
             for k, v in referrer.iteritems():
        else :
                 if v is obj:
            for w in ww :
                     result.append(k)
                txt += w.strip()+' '
     return result
        words = patWordSep.split( txt )
         if len(words) > 0 :
            txt = ""           
            line = ''
             for w in words :
                w=w.strip()
                 if len(w) > 0 :
                    if len(line) + len(w) > 80 :
                        lines.append( line )
                        line = w + " "
                     else :
                        line=line+w+" "
            if len( line )>0 :
                lines.append( line )
 
    else :
        ww = text.split('\n')
        if len(ww) == 0 :
            lines.append( text )
        else :
            for w in ww :
                lines.append( w )
 
    txt = ''
    for line in lines :
        txt += tab+line+"\n"
     return txt
</source>
</source>


== [[XML avec xml.dom.minidom]] ==
=== Obtenir le nom de la fonction ===
== [[XML avec xml.sax.xmlreader]] ==


== Tkinter : la bibliothèque graphique ==
==== Nom de fichier,  n° de ligne, nom de fonction sur plusieurs niveaux ====
* [[Tkinter:Index]]
{{parW|1=
{{code|lang=python|code=
import sys
import inspect
 
def getFrameStr( fr  ):
    _, fileName = os.path.split( fr.f_code.co_filename )
    fname = fr.f_code.co_name
    line = fr.f_lineno
    return "%s(%d).%s" % (fileName,line,  fname)
def pfname():
    src1 = ""
    src2 = ""
    src3 = ""   
    nb = len(inspect.stack())
    print( nb )
    if nb > 2 :
        src1 = getFrameStr( sys._getframe(3) )
    if nb > 1 :   
        src2 = getFrameStr( sys._getframe(2) )
    if nb > 0 :   
        src3 = getFrameStr( sys._getframe(1) )
    print( "%s %s %s : " %(src1,src2,src3), end="" )


== {{id|install}}Installation ==
=== Installation de librairies  ===
==== Seulement pour un utilisateur ====
{{parW|1=
{{code|lang=bash|code=
python setup.py install --user
}}
}}
}}
}}
=== {{id|compile}}Installation avec compilation des modules écrits en C ===
==== Fonction courante ====
==== Sous WINDOWS ====
<source lang="python">
{{parW|1=
def pfname( self ):
Le mieux est d'installer Visual Studio avec l'option {{dq|Python tools ...}} en choisissant l'option {{dq|Installation personnalisée}}
    print self.__class__.__name__,sys._getframe().f_code.co_name
}}
</source>
==== Sous Linux ====
 
{{parW|1=
<source lang="python">
* [[Compilation:Index#Exemple_:_compilation_aes_pour_python_2.5| Exemple : compilation aes pour python 2.5]]
def func_name():
* [[alo-aes]]
    return sys._getframe(1).f_code.co_name
}}
</source>


== pylint ==
==== Fonction appelante ====
{{parW|1=
<source lang="python">
<source lang="python">
pylint --generate-rcfile  > ~/.pylintrc
def pfname( self ):
    print self.__class__.__name__,sys._getframe(1).f_code.co_name
</source>
</source>
}}
 
== Annotation des functions - typage des arguments  ==
Voir aussi [[#error_in_function|error_in_function]]
 
 
 
==== Liens ====
*[http://code.activestate.com/recipes/66062/ www.activestate.com (Recipe 66062: Determining Current Function Name) ]
 
== utilisation des feuilles excel ==
{{parW|1=
{{parW|1=
Il est recommandé d'adopter les conventions suivantes pour améliorer la lisibilité du code :
* Lien vers les modules (source) :
{{code|lang=python|code=
*: http://www.python-excel.org/
def send_email(address,    # type: Union[str, List[str]]
}}{{parW|1=
               sender,      # type: str
Working with Excel Files in Python
               cc,          # type: Optional[List[str]]
This site contains pointers to the best information available about working with Excel files in the Python programming language.
}}{{parW|1=
The Packages
There are python packages available to work with Excel files that will run on any Python platform and that do not require either Windows or Excel to be used. They are fast, reliable and open source:
 
Download | Documentation | Bitbucket
 
* openpyxl
*: The recommended package for reading and writing Excel 2010 files (ie: .xlsx)
*: Download https://pypi.python.org/pypi/openpyxl
*: Documentation https://openpyxl.readthedocs.io/en/default/
*: Bitbucket https://bitbucket.org/openpyxl/openpyxl
 
* xlsxwriter
* An alternative package for writing data, formatting information and, in particular, charts in the Excel 2010 format (ie: .xlsx)
*: Download
*: Documentation
*: Bitbucket
 
* xlrd
*: This package is for reading data and formatting information from older Excel files (ie: .xls)
*:
 
* xlwt
*: This package is for writing data and formatting information to older Excel files (ie: .xls)
*:
 
* xlutils
*: This package collects utilities that require both xlrd and xlwt, including the ability to copy and modify or filter existing excel files.
*: NB: In general, these use cases are now covered by openpyxl!
 
}}
 
== clipboard - presse-papier ==
=== le module clipboard ===
{{parW|1=
{{code|lang=python|code=
import clipboard
 
clipboard.copy("abc")  # now the clipboard content will be string "abc"
 
text = clipboard.paste()  # text will have the content of clipboard
}}
source  : https://pypi.python.org/pypi/clipboard/0.0.4
il faut aussi : https://pypi.python.org/pypi/pyperclip
}}
=== Exemple d'application : copier le chemin du fond d'écran de gnome dans le clipboard  ===
{{parW|1=
 
{{code|lang=bash|code=
#!/bin/bash
the_bash_file=$0
the_bash_file_dir_name=$(realpath `dirname "$the_bash_file"`)
the_bash_file_base_name=`basename "$the_bash_file"`
 
imgpath=$(gsettings get org.gnome.desktop.background picture-uri)
 
python ${the_bash_file_dir_name}/toClipBoard.py "${imgpath}"
}}
 
{{code|lang=python|code=
#!/bin/python
import os
import sys
import clipboard
clipboard.copy(sys.argv[1][1:-1])
}}
}}
 
== Texte ==
=== Supprimer les accents ===
<source lang="python">
import unicodedata
 
def strip_accents(ss):
  s=ss
  return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')
</source>
 
=== rearrange_text ===
<source lang="python">
patWordSep=re.compile("\s+", re.DOTALL )
def rearrange_text( text, tab, rearrange_lf=0 ):
    lines = list()
    if rearrange_lf :
        txt = ''
        ww = text.split('\n')
        if len(ww) == 0 :
            txt = text
        else :
            for w in ww :
                txt += w.strip()+' '
        words = patWordSep.split( txt )
        if len(words) > 0 :
            txt = ""           
            line = ''
            for w in words :
                w=w.strip()
                if len(w) > 0 :
                    if len(line) + len(w) > 80 :
                        lines.append( line )
                        line = w + " "
                    else :
                        line=line+w+" "
            if len( line )>0 :
                lines.append( line )
 
    else :
        ww = text.split('\n')
        if len(ww) == 0 :
            lines.append( text )
        else :
            for w in ww :
                lines.append( w )
 
    txt = ''
    for line in lines :
        txt += tab+line+"\n"
    return txt
</source>
 
== [[XML avec xml.dom.minidom]] ==
== [[XML avec xml.sax.xmlreader]] ==
 
== Tkinter : la bibliothèque graphique ==
* [[Tkinter:Index]]
 
== {{id|install}}Installation ==
=== Installation de librairies  ===
==== Seulement pour un utilisateur ====
{{parW|1=
{{code|lang=bash|code=
python setup.py install --user
}}
}}
=== {{id|compile}}Installation avec compilation des modules écrits en C ===
==== Sous WINDOWS ====
{{parW|1=
Le mieux est d'installer Visual Studio avec l'option {{dq|Python tools ...}} en choisissant l'option {{dq|Installation personnalisée}}
}}
==== Sous Linux ====
{{parW|1=
* [[Compilation:Index#Exemple_:_compilation_aes_pour_python_2.5| Exemple : compilation aes pour python 2.5]]
* [[alo-aes]]
}}
 
== pylint ==
{{parW|1=
<source lang="python">
pylint --generate-rcfile  > ~/.pylintrc
</source>
}}
== Annotation des functions - typage des arguments  ==
{{parW|1=
Il est recommandé d'adopter les conventions suivantes pour améliorer la lisibilité du code :
{{code|lang=python|code=
def send_email(address,    # type: Union[str, List[str]]
               sender,      # type: str
               cc,          # type: Optional[List[str]]
               bcc,        # type: Optional[List[str]]
               bcc,        # type: Optional[List[str]]
               subject='',
               subject='',
               body=None    # type: List[str]
               body=None    # type: List[str]
               ):
               ):
     # type: (...) -> bool
     # type: (...) -> bool
     """Send an email message.  Return True if successful."""
     """Send an email message.  Return True if successful."""
     ...
     ...
}}
{{code|lang=python|code=
from typing import List
 
class Example:
    def method(self,
              lst,      # type: List[str]
              opt=0,    # type: int
              *args,    # type: str
              **kwargs  # type: bool
              ):
        # type: (...) -> int
        """Docstring comes after type comment."""
        ...
}}
* source
*: http://mypy.readthedocs.io/en/latest/python2.html#multi-line-python-2-function-annotations
* pep-0484
*: https://www.python.org/dev/peps/pep-0484
}}
 
== PyHelp ==
{{parW|1=
* [[PhHelp]]
}}
 
== Utilisation de python dans le monde du web (World Wide Web) ==
=== [[mod_python|Apache/Python Integration (mod_python)]] ===
=== [[mod_wsgi|Apache/Python Integration (mod_wsgi)]] ===
=== [[Twisted||Apache/Python Integration Twited]] ===
=== Liens ===
{{parW|1=
* [http://docs.python.org/howto/webservers.html?highlight=mysql HOWTO Use Python in the web]
* [http://wiki.python.org/moin/WebProgramming Web Programming in Python]
}}
}}
{{code|lang=python|code=
from typing import List


class Example:
== Adaptateur Pyhton (wrapper, banding) pour d'autres langages - Bindings - Wrapping  ==
    def method(self,
              lst,     # type: List[str]
              opt=0,    # type: int
              *args,    # type: str
              **kwargs  # type: bool
              ):
        # type: (...) -> int
        """Docstring comes after type comment."""
        ...
}}
* source
*: http://mypy.readthedocs.io/en/latest/python2.html#multi-line-python-2-function-annotations
* pep-0484
*: https://www.python.org/dev/peps/pep-0484
}}
 
== PyHelp ==
{{parW|1=
* [[PhHelp]]
}}
 
== Utilisation de python dans le monde du web (World Wide Web) ==
=== [[mod_python|Apache/Python Integration (mod_python)]] ===
=== [[mod_wsgi|Apache/Python Integration (mod_wsgi)]] ===
=== [[Twisted||Apache/Python Integration Twited]] ===
=== Liens ===
{{parW|1=
{{parW|1=
* [http://docs.python.org/howto/webservers.html?highlight=mysql HOWTO Use Python in the web]
* [https://realpython.com/python-bindings-overview Python Bindings: Calling C or C++ From Python]
* [http://wiki.python.org/moin/WebProgramming Web Programming in Python]
* [https://docs.python.org/3/extending/extending.html Extending Python with C or C++]
* [https://pypi.org/project/dlsym/ dlsym – A cross-platform symbol locator]
}}
}}



Version actuelle datée du 18 décembre 2024 à 14:07

Version : 1.36.1 4878 (2024-12-18) 20241218140708
Auteurs :
Arthur TOROSSIAN
Résumé :
Cette page contient une information concise sur le langage python.

1 Priorité des opérateurs (precedence)

Par oredre croissante :

  • lambda
    Lambda expression
  • if else
  • or
  • and
  • not x
  • in, not in, is, is not, <, <=, >, >=, <>, !=, ==
  • |
    Bitwise OR
  • ^
    Bitwise XOR
  • &
    Bitwise AND
  • <<, >>
    Shifts
  • +, -
  • *, /, //, %
  • +x, -x, ~x
    Positive, negative, bitwise NOT
  • **
    Exponentiation
  • x[index], x[index:index], x(arguments...), x.attribute
    Subscription, slicing, call, attribute reference
  • (expressions...), [expressions...], {key: value...}, `expressions...`
    Binding or tuple display, list display, dictionary display, string conversion
docs.python.org

2 Les types

2.1 Les constantes

class indCont(IntEnum):
    @classmethod
    def nm( name, defVal=None):        
        return getattr( name , defVal )

class gbI(indCont):
    dH             = 0  # gbI.dH deltaHeight
    dT             = 1  # gbI.dT
    dTcMax         = 2  # gbI.dTcMax
    dWaterFlowMax  = 3  # gbI.dWaterFlowMax
    dl             = 4  # gbI.dl
    upLevel        = 5  # gbI.upLevel
    downLevel      = 6  # gbI.downLevel
    wettedLength   = 7  # gbI.wettedLength
    dryLength      = 8  # gbI.dryLength
    emergedLength  = 9  # gbI.emergedLength  -> flt.emergedLength
    immergedLength = 10 # gbI.immergedLength -> flt.immergedLength
    filterFlow     = 11 # gbI.filterFlow -> flt.waterFlow
    imFlow         = 12 # gbI.imFlow -> flt.imFlow
    emFlow         = 13 # gbI.emFlow -> flt.emergedFlow
    wetTc          = 14 # gbI.wetTc -> flt.wettedTc

if __name__ == '__main__':
    #---------------------------------------------------------------------------
    print( gbI )
    print( list(gbI) )
    print( "dT", gbI( gbI.dT) )
    print( "downLevel", getattr( gbI, "downLevel" , None ))
    print( "immergedLength", gbI.nm( "immergedLength") )
    print( gbI.dH.name,  gbI.dH )
    print( gbI.dT.name, gbI.dT )
    try :
        gbI.dH = 4
    except AttributeError as err :
        print(err)

2.2 Les dates

2.2.1 git/pythonTool/pattern.py

#-------------------------------------------------------------------------------
import time # https://docs.python.org/fr/3/library/time.html#time.gmtime
# L'epoch est le point de départ du temps, le résultat de time.gmtime(0) est 
# le 1er janvier 1970 à 00:00:00 
#-------------------------------------------------------------------------------
def getTimeAsFloat() :
    return time.time() # absolue time in seconds
#-------------------------------------------------------------------------------
def getTimeAsStr( fmt ):
    return time.strftime("%Y/%m/%d_%H:%M:%S",fmt)
#-------------------------------------------------------------------------------
timeSec = getTimeAsFloat()              # time in seconds 
gmtTime = time.gmtime( timeSec )        # gmt Greenwich Mean Time 
                                        # (Temps moyen de Greenwich)
locTime = time.localtime( timeSec )     # local time
#-------------------------------------------------------------------------------
print( "(s) time", timeSec ) 
print( "gmt time", getTimeAsStr( gmtTime ) ) 
print( "loc time", getTimeAsStr( locTime ) )
(s) time 1734213182.5401628
gmt time 2024/12/14_21:53:02
loc time 2024/12/14_22:53:02

2.2.2 get_datetime_str

def get_datetime_str():
    return time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
def get_date_year( date ):
    return time.strftime("%Y",date)

def get_date_month( date ):
    return time.strftime("%m",date)

def get_date_day( date ):
    return time.strftime("%d",date)

2.2.3 date_str2date_float

def date_str2float( sdate ):
    ds = time.strptime( sdate,"%d/%m/%Y"  )
    d = time.mktime( ds )
    return d

2.2.4 date_float2date_str

def date_float2date_str( d ):
    ds = time.strftime("%d/%m/%Y", time.gmtime(d) )
    return ds

2.2.5 date_float_add_days

def date_float_add_days( d, nb ):
    nd = d + 3600*24*nb
    return nd

2.2.6 time2str str2time getAcTimeOfFile timeToFile fileToTime

timeForat = "%Y-%m-%d_%H-%M-%S"
def time2str( t=None ):
    st = time.localtime( t )
    return time.strftime( timeForat , st )
def str2time( text ) :
    st = time.strptime( dT, timeForat )
    return time.mktime( st )
def getAcTimeOfFile( filename ):
    infoStat = os.stat( filename )
    st = time.localtime( infoStat.st_atime )
    t = time.mktime( st )
    return t
def timeToFile( filename, t ):
    dT = time2str( t )
    tofile( filename, dT )
def fileToTime( filename ):
    dt = fromfile( filename )

3 Système et codage das chaînes de caractères

Parfois le codage avec le système a des problèmes :

print(sys.getdefaultencoding())
print(sys.stdout.encoding)
#!/usr/bin/python
# -*- coding: UTF-8 -*-

print( "OS encoding : ", locale.getpreferredencoding())

Pour python3 :

def printRaw( *text ):
    myout = open(1, "w", encoding = "UTF-8", closefd = False)
    print(*text, file=myout)
    myout.flush()
    myout.close()

4 Programme

4.1 Versionnement

4.1.1 Obtenir la signature numérique (hashage sha) du versionnement par git

4.1.1.1 subprocess.check_output - git describe or git show
def getVersionningSignature(  ):
    try : 
        # label = "-"+subprocess.check_output(["git", "describe"]).strip(
        # ).decode('utf-8')
        sign = "_sha_"+subprocess.check_output(
                            ["git", "show","-s","--format=%h"]).decode('utf-8')    
    except FileNotFoundError as err :
        sign = "".encode('utf-8')
    return sign.strip()
4.1.1.2 subprocess.check_output - git rev-parse HEAD
import subprocess
def get_git_revision_hash() -> str:
    return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').strip()

def get_git_revision_short_hash() -> str:
    return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip()
4.1.1.3 gitpython
pip install gitpython
import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

4.1.2 Application

################################################################################
# release.V1.V2.V3.V4
# release x(n), rpa, ra, rb, rc(n), rl :
#         x(n) : x1 x2 , x3 ... x400 ... (in development)
#         rpa  : Release Pre-Alpha for unit or intergation tests
#         ra   : release alpha final tests in development team "recette usine"
#         rb   : release beta test in client test team "recettes métier"
#         rc(n): release candidate 1, 2, 3, ... test in client test team
#         rl   : release live "live release" or gd (gold) or pr (prod)
# 
#         V1 : architecture modification
#         V2 : function modifications
#         V3 : implementation of functions
#         V4 : bug corrections 
VERSION = "x1-0.0.0.0"
################################################################################
APP_PATH, APP_NAME = os.path.split(__file__)

4.1.3 Library

#!/usr/bin/python
# -*- coding: UTF-8 -*-
################################################################################
# API identification file with list of interface published and accessible items.
################################################################################
# module identification file with api sub module.
#
# [release-]current.revision.age
#
# [release-]apiVersion.revisionOfThisVersion.ageOfThisApi
#
# exemple : 3.1.2
#             if you use API 1.x.x you can use it : 3-2=1 
# current :
#         interface, API version
# revision:
#         implementation of API version
# age     :
#         ascendant compatibility between API
#         versions compatible width API : current, current-1, ...(current - age) 
#
# release x(n), rpa, ra, rb, rc(n), rl :
#         x(n) : x1 x2 , x3 ... x400 ... (in development)
#         rpa  : Release Pre-Alpha for unit or intergation tests
#         ra   : release alpha final tests in development team "recette usine"
#         rb   : release beta test in client test team "recettes métier"
#         rc(n): release candidate 1, 2, 3, ... test in client test team
#         rl   : release live "live release" or gd (gold) or pr (prod)
VERSION = "x1-0.0.0"
ABSTRACT_MSG="call of abstract method"

4.2 En-tête

#!/usr/bin/python
# -*- coding: UTF-8 -*-

4.3 main

if __name__ == '__main__' :    
    pass

4.4 minmal

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys, re

if __name__ == '__main__' :    
    pass

4.5 Exception, raise, try

4.5.1 solution élégante pour tracer et informer

Exemple d'utilisation

def debugInfo( pm ):
        global debugIndex
        traceback.format_stack()
        # frame,filename, num, func = inspect.getouterframes(
        #                                     inspect.currentframe())[1][:4]
        debugIndex += 1
        print("")
        print("id(pm)", id(pm) )
        print("debugIndex",debugIndex)
        for ll in traceback.format_stack()[:-1] :
            print( "    "+ll )
        print(pm)
        print("%s" %(pm.onGetInfo))
        print("%s %s" %(pm.pressureDropMaxTime, pm.pressureDropMax ))
        print("Enter");input()


import traceback
import sys
from testLib import exceptionProcess
                
def myFunction2( a ):
    myFunction( a )

class MyClass :
    def __init__(self,a):
        self.a = a
    def do(self):
        try :
            a = self.a / 0             
        except Exception as err :
            errMsg = exceptionProcess(err, sys.exc_info(), 
                                                    traceback.format_stack() )
            print(errMsg)
            exit(1)
        
def myFunction( a ):
    cl = MyClass(a)
    cl.do()
    print("End of myFunction")        
        
if __name__ == '__main__' :
    pass
    myFunction2( 3 )


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import inspect
import traceback
################################################################################
def exceptionProcess(err, exeInfo, lastStack ):
    """
import sys
import traceback
import inspect
    
use :
errMsg = exceptionProcess(err, sys.exc_info(), traceback.format_stack() )
"""    
    frame,filename, num, func = inspect.getouterframes(
                                            inspect.currentframe())[1][:4]    
    last =  traceback.format_list(traceback.extract_tb(exeInfo[2]))[0]
    history = lastStack
    txt = ""
    for x in history[:-1] :
        txt += x
    txt += last
    txt += "catched p:%s\nline:%s func:%s\n" % (filename, num, func)    
    txt += "ERROR " + str(err)    
    return txt
################################################################################

4.5.2 Obtenir nom de fichier, numéro de ligne et nom de fonction

4.5.2.1 Cas simple mais non utile
import inspect

raisehead = "Error in %s:%s:%s\n" %inspect.getframeinfo(inspect.currentframe())[:3]
raise xmlBaseError("%sNo valid cardinality=%s for node named grammar in grammar" %(raisehead,node_nb))
4.5.2.2 Obtenir nom de fichier, numéro de ligne et nom de fonction de l'appelant
class xmlBaseError( Exception ) :
    def __init__(self, value):
        frame,filename, num, func = inspect.getouterframes(inspect.currentframe())[1][:4]
        path, name = os.path.split(filename)
        head="%s:%s:%s\n    " % ( name, num, func)
        self.value = head+value
    def __str__(self):
        return self.value

4.5.3 Un exemple simple pour tout exceptions en affichant la trace

#!/usr/bin/env python

try :
    raise ...

except SomeException as err:
    errtrbk = traceback.format_exc()
    print "ERROR:\n%s\%s" %(str(err),errtrbk))

    print u"MyException raised", e.__class__.__name__, e
else :
    print u"Unkown exeption :"

4.5.4 Un exemple avec importation

exception_test.py  :

class MyException( Exception ) :
    pass

fonctions.py :

from exception_test import MyException

def f() :
    raise MyException(u"test")

raise.py :

#!/usr/bin/env python

from exception_test import MyException
from fonctions import f

try :
    f()
except MyException,e :
    print u"MyException raised", e.__class__.__name__, e
else :
    print u"Unkown exeption"


Résultats :

MyException raised MyException test

4.6 Options en ligne de commande

#!/usr/bin/python
# -*- coding: ISO8859-1 -*-

import os,sys, getopt

################################################################################
# Help
################################################################################
def help() :
    print u"""\
Help on %(app)s :
-------------------    
%(app)s -x -x AAA --XXXX --XXXX AAAA  
    -h :
        print this help
    """ % ({"app":__file__})   
################################################################################
# Main
################################################################################

if __name__ == '__main__' :
    short = u"xh"
    long = []
    opts,args=getopt.getopt( sys.argv[1:],short, long)
    options = list()
    for opt,val in opts:
        options.append( opt )
    
    for opt,val in opts:
        #if opt==u'-x' :
        #    ...        
        #if opt==u'--XXXXXX' :
        #    ...   
        pass

    if (len(args)==0) and (len(opts)==0) :
        options.append( u"-h" )

    if u'-h' in options  :
        help()
    else :
        # lauch requests ...
        pass

googWay

4.7 Options en ligne de commande : getopt, help, CParams

generated by gen_main_options.py :

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#***********************************************************
"""\
TODO
"""
import os
import sys
import getopt
#import string
#import re
#import time
#import shutil
################################################################################
# Version
################################################################################
APP_PATH, APP_NAME = os.path.split(__file__)
VERSION = u"0.1.0"
################################################################################
# Exceptions
################################################################################
class CAppException(Exception):
    """\
the exception class of the module
    """
    pass
################################################################################
# The process
################################################################################
def do_someThing(params):
    """\
the main process
    """
    print params.longParamVal
    raise CAppException("not good for us")
################################################################################
# params
################################################################################
class CParam(object):
    """\
parameters of the process
    """
    def __init__(self):
        """\
initialize all default values of parameters
        """
        self.errorMsg = ""
        self.shortParamBool = None
        self.shortParamVal = None
        self.longParamBool = None
        self.longParamVal = None

    def write_errorOnStdOutput(self):
        """\
print the parameter errors
        """
        for ms in self.errorMsg.split('\n'):
            if ms.strip() != "":
                print "ERROR: %s" % ms
        exit(1)

    def checkParam(self):
        """\
check parameters
        """
        ok = True
        self.errorMsg = ""
        if self.shortParamBool != None:
            ok = True
            self.errorMsg += " ... \n"

        if self.shortParamVal != None:
            ok = True
            self.errorMsg += " ... \n"

        if self.longParamBool != None:
            ok = True
            self.errorMsg += " ... \n"

        if self.longParamVal != None:
            ok = True
            self.errorMsg += " ... \n"
        if not ok:
            self.write_errorOnStdOutput()
        return ok

################################################################################
# Help
################################################################################
def write_helpOnStdOutput():
    u"""\
print the help of the application
    """
    print u"""
Help on %(app)s:
-------------------
* %(app)s version %(version)s
    %(app)s -h

* Options:
    -h:
      Print this help.
    -b
      ...
    -v <val>
      ...
    --longBool
      ...
    --longVal <val>
      ...""" % ({u"app": APP_NAME, u"version": VERSION})

################################################################################
# Main
################################################################################
def executeMainProcess():
    """\
    execute main process
    """
    try:
        appParam = CParam()
        shortOption = u"hsv:"
        longOption = [u"longBool", u"longVal="]
        dohelp = False

        opts = getopt.getopt(sys.argv[1:], shortOption, longOption)[0]

        for opt, val in opts:

            if opt == u'-h':
                dohelp = True
                write_helpOnStdOutput()

            if opt == u'-s':
                appParam.shortParamBool = True

            if opt == u'-v':
                appParam.shortParamVal = val

            if opt == u'--longBool':
                appParam.longParamBool = True

            if opt == u'--longVal':
                appParam.longParamVal = val

            else:
                pass

        appOk = appParam.checkParam()
        if (not dohelp) and appOk:
            do_someThing(appParam)

    except Exception as ex:
        info = sys.exc_info()
        raise CAppException("\nERRORS %s" % str(ex)), None, info[2]

if __name__ == u'__main__':
    executeMainProcess()

4.8 execute - command - popen

Al1
Attention16.png
Utiliser plutôt subrocess (os.pepen est obsolète)
def execute( command  ) :
    print "cmd : ", command
    e = os.popen( command + " 2>&1" , "r" )
    out = e.read()    
    rc =  e.close()
    if rc == None :
        rc= 0
    std_out = out
    std_err="See Standard out"
    return rc, std_out, std_err

En mode pas à pas; interception de la sortie standard en cours

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import subprocess
import sys
pat = re.compile("(\d\/\d)")
def do(exe):
    sys.stdout.flush()
    try:
        p = subprocess.Popen(exe, stdout = subprocess.PIPE, stderr = \
                                                subprocess.STDOUT, shell = True)
    except Exception as err:
        print err
        sys.stdout.flush()
    encore = True
    while(encore):
        retcode = p.poll()  # returns None while subprocess is running
        sys.stdout.flush()
        line = p.stdout.readline()
        val = pat.findall(line)
        if len(val) > 0:
            print val[0]
        sys.stdout.flush()
        encore = retcode == None
    print "end"
if __name__ == '__main__':
    print "start"
    do("python cmd.py")
    print "end"

le programme cmd.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import time
nb = 10
for x in range(nb):
    print "toto %d/%d" % (x, nb)
    sys.stdout.flush()
    time.sleep(1.0)

4.9 execute - command - subprocess - popen

def executeInShell( shellcmd  ) :
    process = subprocess.Popen( shellcmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE )    
    stdoutdata, stderrdata = process.communicate()        
    return process.returncode, stdoutdata, stderrdata


Exécution en mode synchrone avec capture progressive de

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import subprocess
import sys
# patTelemacIteration = re.compile("(\d+\/\d+)")
patTelemacIteration = re.compile("ITERATION +(\d+) +TEMPS")

def executeExternalShellCommand(exe):
    sys.stdout.flush()
    try:
        p = subprocess.Popen(exe, stdout = subprocess.PIPE, stderr = \
                                                subprocess.STDOUT, shell = True)
    except Exception as err:
        print err
        sys.stdout.flush()
    encore = True
    while(encore):
        retcode = p.poll()  # returns None while subprocess is running
        sys.stdout.flush()
        line = p.stdout.readline()
        print line
        val = patTelemacIteration.findall(line)
        print val
        if len(val) > 0:
            print int(val[0])
        sys.stdout.flush()
        encore = retcode == None
    print "end"
if __name__ == '__main__':
    print "start"
    executeExternalShellCommand("cd ...; python cmd.py")
    print "end"
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import time
nb = 10
for x in range(nb):
    print " ITERATION      %d  TEMPS : 15 MN   0.0000 S   (      900.0000 S) IT\
ERATION      200  TEMPS" % (x)
    sys.stdout.flush()
    time.sleep(1.0)

4.9.1 Get directly the output

result = subprocess.check_output("gsettings get org.gnome.desktop.background picture-uri", shell=True)

4.10 isLanched

def isLanched( procName ):
    import psutil, string
    pid = os.getpid()
    patText = re.escape(procName)
    pat = re.compile( ".*%s.*" % patText )
    ok = False
    for proc in psutil.process_iter():
        if pid != proc.pid :
            if pat.match( string.join(proc.cmdline()," ") )  :
                ok=True
    return ok

4.11 Ajouter des répertoire dans le path python en dynamique

import sys
sys.path.append("/home/me/mypy")

5 La commande print

5.1 Afficher sur la sortie d'erreurs (stderr)

print >> sys.stderr, "Error ..."


en Python 3 :

print(5, "toto", file=sys.stderr)


Sa propre fonction:

def conErrOut(*args):
    print(*args, file=sys.stderr, **kwargs)

6 Design pattern, POO, Algorithmes

6.1 POO Programmation orientée objet

6.1.1 class attribute - instance attribute

class CObj(object):
  classAttr = 0
  def __init__(self, name, instance_attr):
    self.name = name
    self.objAttr = instance_attr
  def __str__(self):
    return "%s %s %s %s" %(self.name, self.classAttr, self.objAttr, self.__dict__)

if __name__ == '__main__':
    
    obj1 = CObj("A", 1)
    obj2 = CObj("B", 2)

    
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)
    print( obj1 )
    print( obj2 )
    print()
    
    CObj.classAttr += 1
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)    
    print( obj1 )
    print( obj2 )
    print()

    obj1.classAttr += 1    # ATTENTION PIEGE
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)    
    print( obj1 )
    print( obj2 )
    print()

    obj2.classAttr += 1    # ATTENTION PIEGE
    print (CObj.classAttr)
    print (obj1.classAttr)
    print (obj2.classAttr)    
    print( obj1 )
    print( obj2 )
    print()
	
    CObj.classAttr += 1
    print (CObj.classAttr)	
    print (obj1.classAttr)
    print (obj2.classAttr)    
    print( obj1 )
    print( obj2 )
    print()

    print (CObj.objAttr)   # ERROR
0
0
0
A 0 1 {'objAttr': 1, 'name': 'A'}
B 0 2 {'objAttr': 2, 'name': 'B'}

1
1
1
A 1 1 {'objAttr': 1, 'name': 'A'}
B 1 2 {'objAttr': 2, 'name': 'B'}

1
2
1
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 1 2 {'objAttr': 2, 'name': 'B'}

1
2
2
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 2 2 {'objAttr': 2, 'name': 'B', 'classAttr': 2}

2
2
2
A 2 1 {'objAttr': 1, 'name': 'A', 'classAttr': 2}
B 2 2 {'objAttr': 2, 'name': 'B', 'classAttr': 2}

Traceback (most recent call last):
  File "testP.py", line 55, in <module>
    print (CObj.objAttr)
AttributeError: type object 'CObj' has no attribute 'objAttr'

6.2 Sérialisation

6.2.1 pickle

################################################################################
import pickle
def objToFile(  obj, fileName  ):
    with open(fileName, 'wb') as handle:
        pickle.dump( obj, handle, protocol=pickle.HIGHEST_PROTOCOL)
#-------------------------------------------------------------------------------
def objFormFile(  fileName  ):
    with open(fileName, 'rb') as handle:
        obj = pickle.load(handle)
    return obj
################################################################################

6.3 POO

6.3.1 CDictList

class CDictList :
    def __init__( self, name ) :
        self.name = name
        self.d = dict()
        self.l = list()
        
    def add( self, obj, name  ) :
        if name in self.d :
            raise Exception( 
                    "object named '%s' is already in CDictList named '%s'" 
                    % ( name, self.name ) )
        self.d[ name ] = obj
        self.l.append( obj )

6.4 Génération de code

6.4.1 Générer une fonction

correctionCoefficient=[ (-5000,-5000), (-4000,-4800), (-1000,-3000), (-50,-1000), (0,0), (400, 5), (500, 10), (1000, 1000),(5000, 5000) ]
def createCorrectionFunction(  ) :
    fileName="func.py"
    txt = "#!/usr/bin/python\n"
    txt += "# -*- coding: UTF-8 -*-\n"    
    txt += "def hcorection( val ) :\n"
    txt += "    nval=val\n"
    
    a=correctionCoefficient[0]
    for b in correctionCoefficient[1:] :     
        txt += "    if (val > %d) and (val <=%d) :\n" %( a[0], b[0] )
        txt += "        nval =  ( val- %f )*%f +  %f\n" %( a[0], float(b[1]-a[1])/(b[0]-a[0])  ,a[1] )
        a=b
    txt += "    return nval\n"
    tofile( fileName, txt )

Ce qui donne la fonction suivante :

6.5 Design pattern

6.5.1 Singleton

Voici un petit code écrit en python qui explique comment écrire un singleton en langage python. Notez bien que dans la méthode __init__ il faut faire quelques vérifications notamment avec les listes.

class CSingleton( object ):
    class_instance = None
    def __init__( self, a ):
        print "CSingleton init"
        self.vitesse = a
        if not hasattr( self, "alist") :
            self.alist = list()
    
    def __new__( typ, *args, **kwargs ):
        print "CSingleton new", typ.class_instance        
        if typ.class_instance == None :
            obj = object.__new__( typ, *args, **kwargs)
            typ.class_instance = obj
        else :
            obj = typ.class_instance        
        return obj

    def addObject(self, obj):
        self.alist.append( obj )

if __name__ == '__main__' :
    a = CSingleton( 1 )
    a.addObject( "Lundi" )
    print "a.vitesse=",a.vitesse
    print "a.alist=",a.alist

    b = CSingleton( 2 )
    b.addObject( "Mardi" )
    print "b.vitesse=",b.vitesse
    print "b.alist=",b.alist

    c = CSingleton( 3 )
    c.addObject( "Mercredi" )
    print "c.vitesse=",c.vitesse
    print "c.alist=",c.alist

    print "a.vitesse=",a.vitesse
    print "a.alist=",a.alist
    print "b.vitesse=",b.vitesse
    print "b.alist=",b.alist
    print "c.vitesse=",c.vitesse
    print "c.alist=",c.alist
    print "id(a)=",id(a)
    print "id(b)=",id(b)
    print "id(c)=",id(c)

Ce qui donne :

python singleton.py
CSingleton new None
CSingleton init
a.vitesse= 1
a.alist= ['Lundi']
CSingleton new <__main__.CSingleton object at 0xb7cf8ecc>
CSingleton init
b.vitesse= 2
b.alist= ['Lundi', 'Mardi']
CSingleton new <__main__.CSingleton object at 0xb7cf8ecc>
CSingleton init
c.vitesse= 3
c.alist= ['Lundi', 'Mardi', 'Mercredi']
a.vitesse= 3
a.alist= ['Lundi', 'Mardi', 'Mercredi']
b.vitesse= 3
b.alist= ['Lundi', 'Mardi', 'Mercredi']
c.vitesse= 3
c.alist= ['Lundi', 'Mardi', 'Mercredi']
id(a)= 3083833036
id(b)= 3083833036
id(c)= 3083833036

6.6 Algorithmes

6.6.1 resgression linéaire en 3 dimensions pour obtenir un plan optimum pour une nuage de points

import numpy as np
################################################################################
nbpts = 10 # nombre de points par axe
a = 5. # paramètres du plan
b = 3.
c = 2.
d = 10.
sigma = 0.1 # écart type
################################################################################
def planXyz(x, y, z,  A):
    return A[0]*x + A[1]*y + A[2]*z + A[3]
################################################################################
def lienarRegressionXyz(X,Y,Z):
    points = np.hstack(
            (
                X, Y, Z, np.ones_like(X) 
            ) 
        )
    resultat = np.linalg.lstsq(points, T)
    aopt, bopt, copt, dopt = resultat[0]
    erreur = resultat[1][0]/(nbpts*nbpts)
    return  aopt, bopt, copt, dopt,erreur 
################################################################################
x = np.linspace(0, 1, nbpts)
y = np.linspace(0, 1, nbpts)
z = np.linspace(0, 1, nbpts)

grilleX, grilleY, grilleZ = np.meshgrid(x, y, z)
################################################################################
X = grilleX.flatten().reshape(nbpts*nbpts*nbpts, 1)
Y = grilleY.flatten().reshape(nbpts*nbpts*nbpts, 1)
Z = grilleZ.flatten().reshape(nbpts*nbpts*nbpts, 1)
T = planXyz(X, Y, Z,  (a, b, c, d)) + sigma*np.random.randn(nbpts*nbpts*nbpts, 
                                                                            1)
################################################################################
a,b,c,d,e = lienarRegressionXyz(X,Y,Z)
print( 
    "a=%f b=%f c=%f d=%f χ²=%f" %( a,b,c,d,e ))

6.6.2 Filtre passe bas - exemple

from scipy import signal
import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 1, 1000, False)  # 1 second
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5

class lpFilter:
    def __init__(self, fc, fe):
        self.fc = fc
        self.fe = fe
        self.τ = 1/fc
        self.Te = 1 / fe
        self.α = self.τ / (self.τ + self.Te)
    
    def filter(self, sig):
        yf_0 = sig[0] 
        yf_1 = yf_0
        yf = list()
        for y in sig:
            yf_0 = self.α * yf_1 + (1-self.α)* y 
            yf_1 = yf_0
            yf.append(yf_0)
        return yf

flp = lpFilter( 15, 1000 )
yf = flp.filter( sig )

plt.plot(t, yf, label='yf')
plt.plot(t, sig, label='sig')
plt.legend()
plt.show()


Fig. n°2 Exemple filttre linéaire

Utilisation de ellip :

from scipy import signal
import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 1, 1000, False)  # 1 second
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5

sos = signal.ellip(8, 1, 100, 5, 'lowpass', fs=1000, output='sos')
filtered = signal.sosfilt(sos, sig)

plt.plot(t, filtered)
plt.plot(t, sig)
plt.show()


Fig. n°3 ellip exemple

Diagramme des fréquences:

from scipy import signal
import matplotlib.pyplot as plt
import numpy as np

b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True)
w, h = signal.freqs(b, a)
 
plt.semilogx(w, 20 * np.log10(abs(h)))
 
plt.title('Elliptic filter frequency response (rp=5, rs=40)')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Amplitude [dB]')
plt.margins(0, 0.1)
plt.grid(which='both', axis='both')
plt.axvline(100, color='green') # cutoff frequency
plt.axhline(-40, color='green') # rs
plt.axhline(-5, color='green') # rp
plt.show()


Fig. n°4 Diagramme des fréquences - ellip exemple

6.6.3 Filtre passe haut - exemple

Utilisation de ellip :

from scipy import signal
import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 1, 1000, False)  # 1 second
sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)+1.5

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.set_title('10 Hz and 20 Hz sinusoids')
ax1.axis([0, 1, -2, 3.5])
 
ax2.set_title('After 17 Hz high-pass filter')
ax2.axis([0, 1, -2, 2])
ax2.set_xlabel('Time [seconds]')
 
sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos')
filtered = signal.sosfilt(sos, sig)
 
ax1.plot(t, sig)
ax2.plot(t, filtered)
plt.tight_layout()
plt.show()

6.6.4 Fonction rapide d'interpolation linéaire - Functor

6.6.5 Adapter Rectangle Dans Zone

def AdapterRectangleDansZone( zone_x,zone_y,zone_l,zone_h, rect_l, rect_h, rlimte ) :
  if (zone_h > 0 ) and (rect_h>0) :
      r1 = zone_l / zone_h
      r2 = rect_l / rect_h
      #print r1,r2
      if r1 >= r2 :
          if rlimte > 0 :
              r =  zone_h / rect_h
              if r > rlimte :
                  r = rlimte
                  hh = round( rect_h*r )
                  ll = round( rect_l*r )
                  newrect_y = zone_y  +( zone_h-hh ) / 2
                  newrect_h = hh
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
                  newrect_l = ll
              else :
                  hh = zone_h
                  ll = round( zone_h*r2 )
                  newrect_y = zone_y
                  newrect_h = hh
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
                  newrect_l = ll
          else :
            hh = zone_h
            ll = round( zone_h*r2 )
            newrect_y = zone_y
            newrect_h = hh
            newrect_x = zone_x  + (zone_l-ll) / 2
            newrect_l = ll
      else :
          if rlimte > 0 :
              r =  zone_l / rect_l
              if r > rlimte :
                  r = rlimte
                  hh = round( rect_h*r )
                  ll = round( rect_l*r )
                  newrect_y = zone_y  +( zone_h-hh ) / 2
                  newrect_h = hh
                  newrect_x = zone_x  + ( zone_l-ll ) / 2
                  newrect_l = ll
              else :
                  ll = zone_l
                  hh = round( ll/r2 )
                  newrect_x = zone_x
                  newrect_l = ll
                  newrect_y = zone_y  + ( zone_h-hh ) / 2
                  newrect_h = hh
          else :
              ll = zone_l
              hh = round( ll/r2 )
              newrect_x = zone_x
              newrect_l = ll
              newrect_y = zone_y  + ( zone_h-hh ) / 2
              newrect_h = hh
  else :
      newrect_x = zone_x
      newrect_l = 0
      newrect_y = zone_y
      newrect_h = 0

  return newrect_x,newrect_y,newrect_l,newrect_h

6.6.6 Fonction de comparaison pour les tri : sort

6.6.6.1 Avec python 2

La comparaison suivante range dans l'ordre des valeurs croissantes:

def myCmp(pntA, pntB):
    rc = 0
    if pntA < pntB:
        rc = -1
    elif pntA > pntB:
        rc = 1
    return rc

vals = [ 1, 5, 6, 0, -15 ]
vals.sort(myCmp)
print vals

ce qui donne :

[-15, 0, 1, 5, 6]
6.6.6.2 Avec Python 3

Le tri se fait dans l'ordre croissant !

Pour les tuples ou listes imbriqués, tri sur l'indice n

myList = sorted(myList, key = lambda els: els[n])


sprocketTeethPointList1.sort( key = lambda pnt: pnt.angle)

ou

sprocketTeethPointList1 = sorted(sprocketTeethPointList1, 
                             key = lambda pnt: pnt.angle)

ou

def angledPointKey(key ):
    return key.angle

sprocketTeethPointList1 = sorted(sprocketTeethPointList1, key = angledPointKey )


ou

def cmpIntAPy3( aa ):
    a = aa.serviceDate
    if a == None :
        a = aa.prototypeDate    
    return a

self.intAs = sorted(self.intAs, key = cmpIntAPy3 )
6.6.6.3 Avec Python 3 à la manière de Python 2
def angledPointClass( myCmpFunc ) :
    class K :
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return myCmpFunc(self.obj, other.obj) < 0
        def __gt__(self, other):
            return myCmpFunc(self.obj, other.obj) > 0
        def __eq__(self, other):
            return myCmpFunc(self.obj, other.obj) == 0
        def __le__(self, other):
            return myCmpFunc(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return myCmpFunc(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return myCmpFunc(self.obj, other.obj) != 0
    return K        

def angledPointCmp(pntA, pntB):
    rc = 0
    pntA = pntA.angle 
    pntB = pntB.angle
    if pntA < pntB:
        rc = -1
    elif pntA > pntB:
        rc = 1
    return rc   

sprocketTeethPointList1.sort( key=angledPointClass(angledPointCmp) )

7 Clavier, Input device

7.1 get_char

voir curses.window.getch() pour une implémentation sous linux.

if os.name=="nt" :
    import msvcrt
    def get_char() :
        if msvcrt.kbhit() :
            return msvcrt.getch()
        else :
            return None
else :
    print "Error : No get_char()"
    exit(1)

7.2 tell me Yes or No

def tellmeYesNo( msg ):
    encore = 1
    choices=['y', 'n', 'yes', 'no']
    schoices='/'.join( choices )
    rep=None
    while encore :
        rep=raw_input( msg+'(%s): ' % schoices ).lower()
        encore = not rep in choices
        if encore :
            print "Choices are : '%s'" %( schoices )
    return rep

8 Interface graphique

8.1 PyQt

8.2 Sous Windows sans console ou terminal

9 Exception et Erreurs

9.1 La bonne façon de gérer les exception pour un débogage

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re, os, sys
class CMyException( Exception ) :
    pass
def raiseCMyException( e, msg ) :
    raise CMyException("\nMyInfo\n"+str(e)).with_traceback(sys.exc_info()[2])
def f1() :    
        a = int( "1" )
        b = int( "1x" )                
def f2():
    try :
        f1()
    except Exception as e :
        # old raise CMyException("\nMyInfo\n"+str(e)), None, info[2]             
        raise CMyException("\nMyInfo\n"+str(e)).with_traceback(sys.exc_info()[2])
def f3():
    f2()            
def f4():
    f3()        
try :
    f4()
except Exception as e :
    raise CMyException("\nMyInfo in main\n"+str(e)).with_traceback(sys.exc_info()[2])

Ce qui donne :

Traceback (most recent call last):
  File "exception.py", line 23, in <module>
    f4()
  File "exception.py", line 21, in f4
    f3()        
  File "exception.py", line 19, in f3
    f2()            
  File "exception.py", line 14, in f2
    f1()
  File "exception.py", line 11, in f1
    b = int( "1x" )                
__main__.CMyException: 
MyInfo in main

MyInfo
invalid literal for int() with base 10: '1x'

9.2 error_in_function

def error_in_function( msg, niv=1 ):
    fonction_name  = sys._getframe(niv).f_code.co_name
    raise Exception( "Error : %s : %s" %( fonction_name, msg )  )

9.3 param_isnot_set

def param_isnot_set( param, param_name ):
    if param == None :
        error_in_function( "%s is not set" % param_name, niv=2 )

9.4 param_isnot_file

def param_isnot_file( pathfilename ):
    if not os.path.isfile( pathfilename ) :
        error_in_function( "'%s' is not a file" % pathfilename, niv=2 )

9.5 param_isnot_dir

def param_isnot_dir( pathdirname ):
    if not os.path.isdir( pathdirname ) :
        error_in_function( "'%s' is not a dir" % pathdirname, niv=2 )

10 Fichiers et répertoires

10.1 Obtenir le contenu d'un répertoire à la manière de Linux

import glob
for path in glob.glob("/home/C07138/.*")+glob.glob( "/home/C07138/*" ) : 
    print path

10.2 Liste des répertoires

#!/usr/bin/python
# -*- coding: ISO8859-1 -*-
import os, sys, re

def tofile( filename, text ) :
    f = open(filename, "w")
    f.write(text)
    f.close()

if __name__ == '__main__' :    
    fs0 = os.listdir('.')
    fs=list()
    for x in fs0 :
        fs.append(x.lower())
    
    fs.sort()
    s=''
    for x in fs :
        if os.path.isdir( x ) :
            s+=x.lower()+" "
    tofile( 'dir_list.txt', s )

10.3 Personnaliser "file object"

class myFileObject :
    def __init__( self, filename, mode="r" ) :
        self.f = open(filename,mode)

    def close(self) :
        return self.f.close()

    def read( self ) :
        txt = self.f.read().replace('\n\r','\n').replace('\r\n','\n').replace('\r','\n')
        return txt

    def write( self, txt ) :
        #txt = txt.replace('\n','\r')
        return self.f.write( txt )

def omypen( filename, mode="r" ) :
    return myFileObject( filename, mode )

10.4 Lire un fichier caractère par caractère

with open(filename,  "r", "UTF-8") as f:
    while True:
        c = f.read(1)
        if not c:
            print("End of file")
            break
        print("Read a character:", c)

10.5 Lire un fichier ligne par ligne

import codecs
ENCODING = "UTF-8"
with codecs.open(param.csvFileName, "r", ENCODING) as csvSrc:
    with codecs.open(csvDstName, "w", ENCODING) as csvDst:
        lineNumber = 0
        for line in csvSrc:
            line = line.replace("\n","").replace("\r","")
            lineNumber += 1

10.6 tofile fromfile

encoding = "UTF-8"
def toTextFile(filename, text):
    with open(filename, "w", encoding=encoding) as fileDesc:
        fileDesc.write(text)

def fromTextFile(filename):
    text = None
    with open(filename, "r", encoding=encoding) as fileDesc:
        text = fileDesc.read()
    return text


def fromTextFileWin(filename):
    text = None
    try : 
        with codecs.open(filename, "r", ENCODING) as fileDesc:
            text = fileDesc.read()
    except Exception as e :
        print("Warning %s" % e)
        print("try %s" % ENCODING2)
        with codecs.open(filename, "r", ENCODING2) as fileDesc:
            text = fileDesc.read()
    return text

10.7 Lire des fichiers ini

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#***********************************************************
# Author:   Arthur TOROSSIAN
# Date:    30.10.2017
#***********************************************************/
import configparser
ABSTRACT_MSG = "call of abstract method"
################################################################################
class CIniFileError(Exception):
    """\
    the main exception class of the module
    """
    pass

def str2bool(v):
    v = v.strip().lower()
    if not v in ["true", "false", "vrai", "faux"]:
        raise CIniFileError("v='%s' is not a valid boolean" % v)
    return (v in ["true", "vrai"])

################################################################################
# CIniParam in order to read ini files
################################################################################
class CIniParam:
    ############################################################################
    def __init__(self):
        self.fileName = None
        self.config = None
        self._currentSection = None
    ############################################################################
    def loadParam(self, fileName):
        self.fileName = fileName
        self.config = configparser.ConfigParser()
        self.config.read(fileName)
        self.getParamFromConfig()

    def getParamFromConfig(self):
        """\
        (API) abstract required API method
        Check all options and attributes validity.
        """
        raise CIniFileError(ABSTRACT_MSG)

    def checkVersion(self, formatSection, v01, v02, v03):
        self.setCurrentSection(formatSection)
        v1 = self.getInt("v1")
        v2 = self.getInt("v2")
        v3 = self.getInt("v3")
        if v1 != v01 :
            errMsg = """

ERROR the file named '%s', in section named '%s', has no the right file format
version. The version must be %d.x.x and the current version is %d.%d.%d
""" % (self.fileName, formatSection, v01, v1, v2, v3)
            raise CIniFileError(errMsg)

    def hasTheSection(self):
        return self.config.has_section(self._currentSection)

    def hasOption(self, optionName):
        return self.config.has_option(self._currentSection, optionName)
    ############################################################################
    def setCurrentSection(self, currentSection):
        self._currentSection = currentSection
        if not self.hasTheSection():
            errMsg = """

ERROR the file named '%s', has no section named '%s'
""" % (
                    self.fileName, self._currentSection)
            raise CIniFileError(errMsg)


    def getFloat(self, varName):
        val = self.loadParamFloat(self._currentSection, varName)
        return val

    def getFloatList(self, varName):
        valList = eval(self.loadParamStr(self._currentSection, varName))
        newVal = list()
        for sf in valList :
            newVal.append(float(sf))
        return newVal

    def getFloatOrNoneList(self, varName):
        valList = eval(self.loadParamStr(self._currentSection, varName))
        newVal = list()
        for sf in valList :
            if sf == None :
                newVal.append(sf)
            else:
                newVal.append(float(sf))
        return newVal

    def getStrList(self, varName):
        valList = eval(self.loadParamStr(self._currentSection, varName))
        newVal = list()
        for sf in valList :
            newVal.append(sf)
        return newVal

    def getInt(self, varName):
        val = self.loadParamInt(self._currentSection, varName)
        return val

    def getBool(self, varName):
        val = self.loadParamBool(self._currentSection, varName)
        return val

    def getStr(self, varName):
        val = self.loadParamStr(self._currentSection, varName)
        return val

    ############################################################################
    def checkNoParam(self, paramName):
        if not self.hasOption(paramName):
            errMsg = """

ERROR the file named '%s', in section named '%s', has no parameter named '%s'
""" % (self.fileName, self._currentSection, paramName)
            raise CIniFileError(errMsg)

    def loadParamFloat(self, sectionName, varName):
        self.checkNoParam(varName)
        xs = self.config.get(sectionName, varName).split("#")[0]
        x = float(eval(xs))
        return x

    def loadParamInt(self, sectionName, varName):
        self.checkNoParam(varName)
        x = int(self.config.get(sectionName, varName).split("#")[0])
        return x

    def loadParamBool(self, sectionName, varName):
        self.checkNoParam(varName)
        dat = self.config.get(sectionName, varName)
        x = str2bool(dat.split("#")[0])
        return x

    def loadParamStr(self, sectionName, varName):
        self.checkNoParam(varName)
        x = self.config.get(sectionName, varName).split("#")[0]
        return x
class CParams(CIniParam) :
    def getParamFromConfig(pm):
        pm.setCurrentSection("param")
        pm.tMax = pm.getFloat("p1")

10.8 fichiers temporaires, tmp, temp

tmp_file=tempfile.NamedTemporaryFile( delete=False )
tmp_file.close()
print tmp_file.name
print os.path.exists(tmp_file.name)
tgzs=fromfile( tmp_file.name )
s.unlink(tmp_file.name)
print os.path.exists(tmp_file.name)

10.9 Lire et écrire des binaires (endianness; little-endian et big-endian) dans des fichiers

On utilise le module struct avec les méthodes unpack et pack :

def scanDatFile( fileName, fileDestinationName, endianness='<', ee1WaterDeep=5, ee1LandHeight=10 ) :
    bs = os.path.getsize( fileName ) 
    fsize = 0    
    fic = open( fileName , 'rb')
    ficDest = open( fileDestinationName , 'wb')
    # < little-endian BYTEORDER LSBFIRST
    # > big-endian
    # h short integer 2 bytes 
    fmt = "%sh" % endianness
    min = 60000
    max = -60000
    noval=-32768
    while fsize < bs :
        fsize += 2
        tmp = fic.read( struct.calcsize(fmt) )
        val, = struct.unpack( fmt , tmp  )    
        valBin = struct.pack( fmt , func.hcorection( val )  )   
        ficDest.write( valBin )        
        #print val
        if val != noval :
            if val < min :
                min = val
            if val > max :
                max = val
    print min, max
    ee1 = ee1WaterDeep + ee1LandHeight
    map = float(max-min+1)
    ee2map = map / ee1
    ee1WaterDeep = round( min/ee2map )
    ee1LandHeight = round( max/ee2map )
    print "Water Deep:%s Land height: %s" %( round( min/ee2map ), round( max/ee2map )  )
    print "Water Cutoff:%s Land Cutoff: %s" %( round( ee1WaterDeep*ee2map ), round( ee1LandHeight*ee2map )  )
    ficDest.close()
    fic.close()

10.10 Lire et écrire des fichiers netCDF

10.11 Copier les dates d'un fichier à un autre

st=os.stat( file1 )
os.utime( file2, (st.st_atime, st.st_mtime) )

10.12 trace

def get_datetime_str():
    return time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())

trace_file_name="trace.txt"
def trace( msg, init=0 ) :
    filename = trace_file_name
    if (os.path.exists( filename ) and (init==0) ):
        f = open( filename, "a"  )
    else :
        f = open( filename, "w"  )
    f.write( "%s %s\n" % (get_datetime_str(),msg) )
    f.close()
trace( "INIT", init=1 )

10.13 get_NewFileName

def get_NewFileName( name, Index=1 ) :
    newname = name    
    name, ext = os.path.splitext( newname  )
    while os.path.exists( newname ) :        
        newname = name + ("%03d" % Index) + ext
        Index += 1
    return newname, Index

10.14 get_NewDictName

patName = re.compile("^(.*?)(\d*)$")
def normName( name  ) :
    nname, ni = patName.findall( name )[0]
    if ni != "" :
        i = int( ni )
        newname = nname + ("%03d" % i)

    else :
        newname = name
    return newname

def normDictNames( namedict ) :
    newD = dict()
    for name, val in namedict.items() :
        newname = normName( name  )
        newD[ newname ] = val
    return newD

def get_NewDictName( name, namedict, Index=1 ) :
    newname = name
    name, i = patName.findall( newname )[0]
    while newname in namedict :
        newname = name + ("%03d" % Index)
        Index += 1
    return newname, Index

utilisation possible  :

dd0 = {"otto":1,"toto3":2, "toto02":4, "tata":5, "toto" :1 }
print dd0
dd = normDictNames( dd0 )
print dd
name, index = get_NewDictName( "toto", dd  )
dd[name] = 30
print name, index, dd
name, index = get_NewDictName( "toto", dd  )
dd[name] = 15
print name, index, dd


{'tata': 5, 'toto': 1, 'toto02': 4, 'toto3': 2, 'otto': 1}
{'toto': 1, 'tata': 5, 'toto002': 4, 'toto003': 2, 'otto': 1}
toto001 2 {'toto003': 2, 'tata': 5, 'toto': 1, 'toto002': 4, 'toto001': 30, 'otto': 1}
toto004 5 {'toto003': 2, 'tata': 5, 'toto004': 15, 'toto': 1, 'toto002': 4, 'toto001': 30, 'otto': 1}

10.15 path_split

def path_split( pathnameext ):
    path, name = os.path.split( pathnameext )
    name , ext = os.path.splitext( name )
    return (path, name, ext,)

10.16 change_path_and_suffix

def change_path_and_suffix(  pathnameext, newpath, suffix ) :
    path, nameext = os.path.split( pathnameext )
    name, ext = os.path.splitext( nameext )
    return newpath + os.sep + name+suffix+ext

10.17 change_path_and_ext

def change_path_and_ext(  pathnameext, newpath, ext ) :
    path, nameext = os.path.split( pathnameext )
    name, ext0 = os.path.splitext( nameext )
    return newpath + os.sep + name+ext

10.18 Get list of files

Simple :

def findFilesInDirectorFromPattern( path, pat ) :
    flist = list() 
    fs = os.listdir(path)
    for x in fs :
        file_path = path+os.sep+x 
        if os.path.isfile( file_path  ) :
            if pat.match( x ) :
                flist.append( file_path  )
    return flist


Évoluée :

def find( flist, path, file_pattern,  subdir, file_exclude_pattern=None, dir_exclude_pattern=None ) :
    fs = os.listdir(path)
    for x in fs :
        file_path = path+os.sep+x
 
        if os.path.isfile( file_path  ) :
            ok=1
            if file_exclude_pattern != None :
                ok = not file_exclude_pattern.match( x )
            if ok and file_pattern.match( x ) :
                print x
                flist.append( file_path  )
 
        if os.path.isdir( file_path  ) :
            if subdir :
                ok = 1
                if dir_exclude_pattern != None :
                    ok= not dir_exclude_pattern.match( x )
                if ok :
                    find( flist, file_path, file_pattern,  subdir, file_exclude_pattern, dir_exclude_pattern)

10.19 Lire et écrire des fichiers HTML

Il ne faut pas utiliser html.parser, Simple HTML ou XHTML parser mais il est largement recommandé d'utiliser sgmllib ou Simple SGML parser.

10.20 Générer une fichier html à partir d'une liste de fichiers sur disques gen_list_html

#!/usr/bin/env python
import re
import os
def gen_list_html( path, file_pattern_txt ) :
    file_pattern = re.compile( file_pattern_txt )
    fs = os.listdir(path)
    fs.sort()
    print "<html><body><ol>"
    for x in fs :
        file_path = path+os.sep+x
        if os.path.isfile( file_path  ) :
            if file_pattern.match( x ) :
                print "<li><a href='%s'>%s</a></li>" %(x,x)

    print "</ol></body></html>"
if __name__ == '__main__' :
    gen_list_html( ".", ".*\.avi$" )

10.21 Générer une fichier html à partir d'une liste d'images/photo sur disques

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys, re, codecs, time, shutil


srcPath = "."
fl = os.listdir(srcPath)
sorted(fl)

f = codecs.open("index.html", "w", encoding = "UTF-8")

f.write("<html style='background-color:#a0a0a0;margin:auto;'>\n")

f.write("""<body 
style='width:210mm;margin:auto;padding:5mm;background-color:#ffffff;'>
<style type="text/css">
p.p {
width:180mm;background-color:#ffffff;margin:auto;
}
td.g {
width:30mm; vertical-align:middle;
}
td.d {
width:150mm; vertical-align:top; background-color:#ffffff;font-size:10pt;
}
img{
width:28mm;
}
</style>
<p class="p">
<table align=center>
""")

for img in fl :
    name, ext = os.path.splitext(img)
    print(name.lower())
    if ext.lower() == ".jpg" :
        f.write("""\
<tr>
    <td class='g'> <img src='%s'> </td>
    <td class='d'> TODO </td>
</tr>
""" % img)

f.write("""
</table>
</p>
</body>
""")
f.write("</html>\n")

f.close()

10.22 gen m3u8 - liste de mp3 - player list - utilisable par Rhythmbox

10.23 genNewNames

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys, re, random

def get_NewFileName( name, Index=1 ) :
    newname = name    
    name, ext = os.path.splitext( newname  )
    while os.path.exists( newname ) :        
        newname = name + ("%03d" % Index) + ext
        Index += 1
    return newname, Index

def genNewNames( path ) :
    index=1
    fs = os.listdir(path)
    nb = len(fs)
    num = 0
    while nb > 0 :
        i = random.randint(0, nb-1 )
        nname = path+os.sep+fs[i]
        del fs[i]
        if os.path.isfile( nname ) :
            nname0, ext = os.path.splitext(nname)
            pname, nname0 = os.path.split(nname)
            rname = pname + os.sep+"im%05d%s" % (num,ext)
            print "  ",nname, rname
            rname, index = get_NewFileName( rname, index )
            os.rename( nname , rname )        
        num += 1
        nb -= 1
        
def genNewNamesInSubDirs( path ) :    
    fs = os.listdir(path)
    for ff in fs :
        pathff = path+os.sep+ff
        print "[%s]" % pathff
        if os.path.isdir( pathff ) :
            genNewNames( pathff )
if __name__ == u'__main__' :    
    genNewNamesInSubDirs( "./Images/listes")   
    genNewNames( "./Images/listeAll" )

10.24 unix2dos

#!/usr/bin/env python
###############
import sys

for fname in sys.argv[1:]:
    infile = open( fname, "rb" )
    instr = infile.read()
    infile.close()
    outstr = instr.replace( "\r\n", "\n" ).replace( "\n\r", "\n" ).replace( "\r", "\n" ).replace( "\n", "\r\n" )

    if len(outstr) == len(instr):
        continue
    
    outfile = open( fname, "wb" )
    outfile.write( outstr )
    outfile.close()

10.25 clean_rep.py

#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
import os
import re
pat_adir = re.compile( "\d{4}" )
pat_mdir = re.compile( "\d{4}-\d{2}" )
def clean_dirs() :
    """
    Delete empty directories with name like AAAA/AAAA-MM or AAAA.
    """
    adirs = os.listdir(".")
    for adir in adirs :
        if pat_adir.match( adir ) :
            mdirs = os.listdir(adir)
            for mdir in mdirs :
                if pat_mdir.match( mdir ) :
                    files = os.listdir( adir+os.sep+mdir )
                    if len(files)==0 :
                        os.rmdir( adir+os.sep+mdir )
            mdirs = os.listdir(adir)
            if len( mdirs )==0 :
                os.rmdir( adir )

if __name__ == '__main__' :
    clean_dirs()

10.26 gen_rep.py

#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-

import os

def gen_dirs() :
    """
    Generate directory with name like AAAA/AAAA-MM if it does not exist.
    """
    for an in range(2000,2012) :
        dir_a = "%04d" %(an)
        if not os.path.exists( dir_a ) :
            os.mkdir( dir_a )
        for m in range(1,13) :
            dir_name = "%s%s%04d-%02d" %(dir_a,os.sep,an,m)
            print dir_name
            if not os.path.exists( dir_name ) :
                os.mkdir( dir_name )

if __name__ == '__main__' :
    gen_dirs()

10.27 size_on_system

def size_on_system( sf, sector_size ):
    if sector_size != None :
        s=0
        ns = sf % sector_size
        if ns == 0 :
            s = sf
        else :
            s = (sf / sector_size) * sector_size  + sector_size
    else :
      s=sf
    return s

10.28 size_of_dir

def size_of_dir( path, sector_size=None  ):
    fs = os.listdir( path )
    s=0
    for f in fs :
        pf = path+os.sep+f
        if os.path.isfile( pf ) :
            statinfo = os.stat( pf )
            s+= size_on_system( statinfo.st_size, sector_size )
        if os.path.isdir( pf ) :
            s+=size_of_dir( pf,sector_size  )
    return s

10.29 sizeOfFile

def sizeOfFile( pathToFile ):
    size = None
    if os.path.isfile( pathToFile ) :
        statinfo = os.stat( pathToFile )
        size = statinfo.st_size
    return size

10.30 have_subdir

def have_subdir( path ) :
    ok = 0
    fs = os.listdir( path )
    nb = len( fs )
    i = 0
    while (i < nb) and (ok==0) :
        pathx = path + os.sep + fs[ i ]
        if os.path.isdir( pathx ) :
            ok = 1
        i += 1
    return ok

11 Compte utilisateur

11.1 get_username

def get_username():
    return getpass.getuser()

11.2 get_hostname

def get_hostname():
    return socket.gethostbyaddr(socket.gethostname())[0]

11.3 get_homedir

def get_homedir():
    homedir = os.path.expanduser('~')
    return homedir

12 Réseau, Internet

12.1 fromurl

def fromurl( cmd ) :
    encore = 1
    while encore :
        try :    
            f = urllib.urlopen( cmd )
            rep = f.read()
            f.close()
            encore = 0
        except Exception,e :
            #print str(e)
            encore = 1
            
    return rep

12.2 socket.setdefaulttimeout

    timeout = 10
    socket.setdefaulttimeout(timeout)
    text = urllib2.urlopen('http://at.bht.fr').read()
    print( text )

12.3 HTTPBasicAuthHandler

    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(
                          realm='My Application',
                          uri='',
                          user='',
                          passwd=''
                          )
    opener = urllib2.build_opener( auth_handler )
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener( opener )    
    text = urllib2.urlopen('https://at.bht.fr/DisEvtSim').read()
    print( text )

12.4 ProxyBasicAuthHandler

    proxy_handler = urllib2.ProxyHandler({'http': 'http://proxypac.edf.fr:3128/','https': 'https://proxypac.edf.fr:3128/'})
    proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
    proxy_auth_handler.add_password('realm', 'proxypac.edf.fr', '', '')
    opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)    
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener(opener)    
    text = urllib2.urlopen('http://at.bht.fr').read()
    print( text )

12.5 ProxyBasicAuthHandler

    proxy_handler = urllib2.ProxyHandler({'http': 'http://proxypac.edf.fr:3128/','https': 'https://proxypac.edf.fr:3128/'})
    proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
    proxy_auth_handler.add_password('realm', 'proxypac.edf.fr', '', '')
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='PDQ Application',
                          uri='https://at.bht.fr/DisEvtSim',
                          user='',
                          passwd='')
    
    opener = urllib2.build_opener(proxy_handler, proxy_auth_handler,auth_handler)    
    # ...and install it globally so it can be used with urlopen.
    urllib2.install_opener(opener)    
    text = urllib2.urlopen('https://at.bht.fr/DisEvtSim').read()
    print( text )

12.6 https sans authentification

    timeout = 10
    socket.setdefaulttimeout(timeout)    
    text = urllib2.urlopen('https://www.google.fr').read()
    print( text )

13 Expressions régulières

13.1 Never match

class CNeverMatch :
    def match( self, f ) :
        return 0

13.2 Allways match

class CAllwaysMatch :
    def match( self, f ) :
        return 1

13.3 Remplacer avec sub : replace_re.py

Un petit programme complet très utile pour traiter les fichiers (utilisation de sub)

#!/usr/bin/python
# -*- coding: 'ISO8859-1' -*-
import os, sys, re

def fromfile( filename ) :
    f = open(filename, "r")
    text = f.read()
    f.close()
    return text

def replace_re( exp, remplacant, txt ) :
    pat=re.compile( exp )
    newtxt= re.sub( pat, remplacant, txt) 
    return newtxt

def replace_re_file( exp, remplacant, filename ) :
    txt = fromfile( filename )
    return replace_re( exp, remplacant, txt ) 

def help() :
    print "HELP"
    print "\treplace_re.py expression_reguliere remplacant filename1 "

if __name__ == '__main__' :    
    if len( sys.argv  ) == 4 :
        txt = replace_re_file( sys.argv[1], sys.argv[2], sys.argv[3] )
        print txt
    else :
        help()

13.4 findall et sub

Le code suivant remplace dans les lignes d'un fichier telles que

<td style="cursor:pointer; background-color: rgb(255, 255, 153); border: 1px solid #CCC;">&nbsp;</a></td>

toutes le chaines &nbsp; par le calcul des couleurs qui se trouvent dans rgb(XXX, XXX, XXX), cela donne dans notre cas :

<td style="cursor:pointer; background-color: rgb(255, 255, 153); border: 1px solid #CCC;" >#ffff99</td>
def rgb( r,v,b ) :
    return "#%02x%02x%02x" %(r,v,b)

def dd( filename ) :
    pattern=re.compile(".*(rgb\(\d+, *\d+, *\d+\));.*")
    pat = re.compile( "&nbsp;" )
    txt = fromfile( filename ).split("\n")
    newtxt=""
    for l in txt :
        tr=re.findall( pattern, l) 
        if len(tr)>0 :
            code=eval(tr[0])
            newl= re.sub( pat, code, l)
        else :
            newl=l
        print newl
        newtxt+=newl

14 Hashage

14.1 crc32 : hashage de lignes de texte ou de binaires

#!/usr/bin/python
#===============================================================================
# -*- coding: UTF-8 -*-
#===============================================================================
import binascii

print("b:")
print( " ", b"hello" )
print( " ", "crc32: %0x" % binascii.crc32(b"hello") )  # bad way -> bytearray
print("bytearray:")
print( " ", bytearray("hello", "utf8" ) )
print( " ", "crc32: %0x" % binascii.crc32( bytearray("hello", "utf8" )))
print("b:")
print( " ", b"barba-papa" )
print( " ", "crc32: %0x" % binascii.crc32 (b"barba-papa" ) )  # bad way -> bytearray
print("bytearray:")
print( " ", bytearray("barba-papa","utf8" ) )
print( " ", "crc32: %0x" % binascii.crc32(  bytearray("barba-papa", "utf8" ) ) )
print()
print( " ", bytearray("Installation on Linux (Obsolète)", "utf8" ) )
print( " ", "crc32: %0x" % binascii.crc32( bytearray("Installation on Linux (Obsolète)", "utf8" )))

15 Les conversions

15.1 Limiter le nombre de chiffres significatifs

def roundToSignificantDigitNumber( x , nbDigit ):
    if x != 0.0 :
        ten = round(math.log10(x))
        tenFac = 10 ** ten
        x = round(x / tenFac,  nbDigit-1)
        x = x * tenFac
    return x

15.2 Convertir les None en nan

On utilise les liste en compréhension :

a = ( None, 1.2, -4 )
b = [ x  if x is not None else float("nan") for x in a ]

on obtient:

[nan, 1.2, -4]

15.3 hexadécimal

def hextoint( x ):
    return int(x,16)
def inttohex( x ):
    return hex(x)

15.4 binaire

a= "{0:08b}".format( a )

ou

def bintoint( x ):
    return int(x,2)

def inttobin( x ):
    return bin(x)

15.5 Couleur vers int (alpha, red, green, blue)

def argbToInt( a, r, g, b ):
    st=struct.pack(">BBBB", a, r, g, b )
    i= struct.unpack(">I", st)[0] 
    return i
def intToArgb( i ):
    print i
    st=struct.pack(">I", i ) 
    return struct.unpack(">BBBB", st)

16 Formatage de texte

16.1 Le principe de la méthode .format

Un exemple pour comprendre rapidement :

"{name1:1.2f} bla bla {name2:02d} {name1:f}".format(name1=3.14, name2=456)

Ce qui produit :

'3.14 bla bla 456 3.140000'

17 Physique

17.1 Nombre de chiffres significatifs

17.2 Rationnels et calculs symboliques / formels

from sympy import Rational
a = Rational(2,3)
print(a)
b = Rational(4,3)
print(a+b)

a=Rational(2*3*5*7*7,2*7*31)
print(a)

sympy.factorint(105)
a = 2*3*5*7*7
b= 2*7*31
sympy.factorint(a)
sympy.factorint(b)
pgcd = sympy.gcd(a,b)
print(pgcd)

aa= a / pgcd
bb= b / pgcd
sympy.factorint(aa)
sympy.factorint(bb)


2/3

2

105
───
 31

{3: 1, 5: 1, 7: 1}
{2: 1, 3: 1, 5: 1, 7: 2}
{2: 1, 7: 1, 31: 1}

14

{3: 1, 5: 1, 7: 1}
{31: 1}


from sympy import symbol
from sympy import symbols
x = symbols("x")
sympy.init_printing(use_unicode=True)
sympy.integrate(sympy.sin(x**2), x)
sympy.integrate(sympy.sin(x**2), (x,-sympy.oo,sympy.oo))
Intégrale :

                ⎛√2⋅x⎞       
3⋅√2⋅√π⋅fresnels⎜────⎟⋅Γ(3/4)
                ⎝ √π ⎠       
─────────────────────────────
           8⋅Γ(7/4)          

√2⋅√π
─────
  2

17.3 Unités

from sympy.physics.units import *
a = 254 * m / s
b =  convert_to(a, [minute])
print(b)
find_unit(kg)
15240*meter/minute

[g, kg, mg, ug, amu, mmu, amus, gram, mmus, grams, pound, pounds, 
kilogram, kilograms, microgram, milligram, micrograms, milligrams, 
planck_mass, milli_mass_unit, atomic_mass_unit, atomic_mass_constant]

17.3.1 Listes des unités

# Dimensionless

percent = percents = Rational(1, 100)
permille = permille = Rational(1, 1000)

ten = Rational(10)

yotta = ten**24
zetta = ten**21
exa = ten**18
peta = ten**15
tera = ten**12
giga = ten**9
mega = ten**6
kilo = ten**3
deca = ten**1
deci = ten**-1
centi = ten**-2
milli = ten**-3
micro = ten**-6
nano = ten**-9
pico = ten**-12
femto = ten**-15
atto = ten**-18
zepto = ten**-21
yocto = ten**-24

rad = radian = radians = 1
deg = degree = degrees = pi/180
sr = steradian = steradians = 1

# Base units

length = m = meter = meters = Unit('meter', 'm')
mass = kg = kilogram = kilograms = Unit('kilogram', 'kg')
time = s = second = seconds = Unit('second', 's')
current = A = ampere = amperes = Unit('ampere', 'A')
temperature = K = kelvin = kelvins = Unit('kelvin', 'K')
amount = mol = mole = moles = Unit('mole', 'mol')
luminosity = cd = candela = candelas = Unit('candela', 'cd')


# Derived units
volume = meter**3
frequency = Hz = hz = hertz = 1/s
force = N = newton = newtons = m*kg/s**2
energy = J = joule = joules = N*m
power = W = watt = watts = J/s
pressure = Pa = pa = pascal = pascals = N/m**2
charge = C = coulomb = coulombs = s*A
voltage = v = V = volt = volts = W/A
resistance = ohm = ohms = V/A
conductance = S = siemens = mho = mhos = A/V
capacitance = F = farad = farads = C/V
magnetic_flux = Wb = wb = weber = webers = J/A
magnetic_flux_density = T = tesla = teslas = V*s/m**2
inductance = H = henry = henrys = V*s/A
speed = m/s
acceleration = m/s**2
density = kg/m**3
optical_power = dioptre = D = 1/m
illuminance = lux = lx = sr*cd/m**2

# Common length units

km = kilometer = kilometers = kilo*m
dm = decimeter = decimeters = deci*m
cm = centimeter = centimeters = centi*m
mm = millimeter = millimeters = milli*m
um = micrometer = micrometers = micron = microns = micro*m
nm = nanometer = nanometers = nano*m
pm = picometer = picometers = pico*m

ft = foot = feet = Rational('0.3048')*m
inch = inches = Rational('25.4')*mm
yd = yard = yards = 3*ft
mi = mile = miles = 5280*ft


# Common volume and area units

l = liter = liters = m**3 / 1000
dl = deciliter = deciliters = deci*l
cl = centiliter = centiliters = centi*l
ml = milliliter = milliliters = milli*l


# Common time units

ms = millisecond = milliseconds = milli*s
us = microsecond = microseconds = micro*s
ns = nanosecond = nanoseconds = nano*s
ps = picosecond = picoseconds = pico*s

minute = minutes = 60*s
h = hour = hours = 60*minute
day = days = 24*hour

anomalistic_year = anomalistic_years = Rational('365.259636')*day
sidereal_year = sidereal_years = Rational('31558149.540')*s
tropical_year = tropical_years = Rational('365.24219')*day
common_year = common_years = Rational('365')*day
julian_year = julian_years = Rational('365.25')*day
draconic_year = draconic_years = Rational('346.62')*day
gaussian_year = gaussian_years = Rational('365.2568983')*day
full_moon_cycle = full_moon_cycles = Rational('411.78443029')*day

year = years = tropical_year


# Common mass units

g = gram = grams = kilogram / kilo
mg = milligram = milligrams = milli * g
ug = microgram = micrograms = micro * g


#----------------------------------------------------------------------------
# Physical constants
#
c = speed_of_light = 299792458 * m/s
G = gravitational_constant = Rational('6.67428') * ten**-11 * m**3 / kg / s**2
u0 = magnetic_constant = 4*pi * ten**-7 * N/A**2
e0 = electric_constant = 1/(u0 * c**2)
Z0 = vacuum_impedance = u0 * c

planck = Rational('6.62606896') * ten**-34 * J*s
hbar = planck / (2*pi)

avogadro_number = Rational('6.02214179') * 10**23
avogadro = avogadro_constant = avogadro_number / mol
boltzmann = Rational('1.3806505') * ten**-23 * J / K

gee = gees = Rational('9.80665') * m/s**2
atmosphere = atmospheres = atm = 101325 * pascal

kPa = kilo*Pa
bar = bars = 100*kPa
pound = pounds = 0.45359237 * kg * gee  # exact
psi = pound / inch ** 2
dHg0 = 13.5951  # approx value at 0 C
mmHg = dHg0 * 9.80665 * Pa
amu = amus = gram / avogadro / mol
mmu = mmus = gram / mol
quart = quarts = Rational(231, 4) * inch**3
eV = 1.602176487e-19 * J

# Other convenient units and magnitudes

ly = lightyear = lightyears = c*julian_year
au = astronomical_unit = astronomical_units = 149597870691*m

18 Math

18.1 Équation de second degré

def secondDegreeEquation(a,b,c):
    # a*x*x + b*y + c = 0
    x1 = None
    x2 = None
    det = b*b - 4 * a * c
    if det>= 0.0 :
        sqDet = math.sqrt(det)
        a2 = a * 2.0
        x1 = (-b - sqDet ) / a2 
        x2 = (-b + sqDet ) / a2
    return x1, x2

18.2 Régression linéaire

source www.science-emergence.com

Fig. n°5: Régression linéaire
from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt

x,y = np.loadtxt("test.txt", unpack='true')

plt.scatter(x,y)

regr = linear_model.LinearRegression()
regr.fit(x[:,np.newaxis], y)

x_test = np.linspace(np.min(x), np.max(x), 100)

plt.plot(x_test, regr.predict(x_test[:,np.newaxis]), color='blue', linewidth=3)

plt.show()

Pour obtenir le coefficient directeur et l'ordonnée à l'origine de la droite:

print 'slope', regr.coef_
print 'intercept', regr.intercept_

donne ici

slope [ 0.80723367]
intercept -0.623011727604

18.3 Décomposition d'un nombre en facteurs premiers

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
def facteurs(n):
    """facteurs(n): décomposition d'un nombre entier n en facteurs premiers"""
    F = []
    if n==1:
        return F
    # recherche de tous les facteurs 2 s'il y en a
    while n>=2:
        x,r = divmod(n,2)
        if r!=0:
            break
        F.append(2)
        n = x
    # recherche des facteurs 1er >2
    i=3
    rn = lsqrt(n)+1
    while i<=n:
        if i>rn:
            F.append(n)
            break
        x,r = divmod(n,i)
        if r==0:
            F.append(i)
            n=x
            rn = lsqrt(n)+1
        else:
            i += 2
    return F
 
# exemple d'utilisation:
print facteurs(100)  # affiche [2,2,5,5]
print facteurs(123456789)  # affiche [3,3,3607,3803]
print facteurs(12345678901234567890) # affiche [2,3,3,5,101,3541,3607,3803,27961L]
 
# et test avec un nombre premier
print facteurs(4291979)  # affiche [4291979]
source: http://python.jpvweb.com/python/mesrecettespython/doku.php?id=decomposition_en_facteurs_premiers

18.4 Histogram - densité de probabilité

18.4.1 Numpy

Utilisation la fonction d’histogramme de numpy voir [2]

Avec l’option {{{1}}} :

Soit n Intervalles I(i) de longueur L(i) et Q(i) la quantité de valeurs incluse dans I(i)

Soit Qt = somme des Qi

Alors l’histogramme avec density=True est la suite des H(i) = Q(i)/L(i)/Qt

Et ainsi l’intégrale de de l’histogramme vaut 1 car c’est la somme de des H(i)*L(i) = somme de Q(i)/Qt = 1

Voici un petit code python pour illustrer :

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
interval = np.linspace(-0.5,1.5,20)
print(interval)
intervalD = np.diff(interval)
print(intervalD)
vals = [ -0.2, 0.1, 0.4, -0.8, 2.8, 0.4 , 6.8, 1.3  ]
hist0 = np.histogram( vals, bins=interval )
hist = np.histogram(  vals, bins=interval , density=True)
print("quantity")
print(hist0[0].tolist())
print("density")
print(hist[0].tolist())
print("integral")
print( np.sum(hist[0]*intervalD)  )

ce qui donne :

[-0.5        -0.39473684 -0.28947368 -0.18421053 -0.07894737  0.02631579
  0.13157895  0.23684211  0.34210526  0.44736842  0.55263158  0.65789474
  0.76315789  0.86842105  0.97368421  1.07894737  1.18421053  1.28947368
  1.39473684  1.5       ]
[0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316 0.10526316 0.10526316 0.10526316 0.10526316 0.10526316
0.10526316]
quantity
[0, 0, 1, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
density
[0.0, 0.0, 1.9, 0.0, 0.0, 1.9, 0.0, 0.0, 3.8, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.8999999999999981, 0.0]
integral
1.0

19 Parallélisme

19.1 multiprocessing

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#***********************************************************

import time
import math
import sys
from multiprocessing import Pool

def getPoreccessorNumber():
    return multiprocessing.cpu_count()

def parallelCall(params):  # a helper for calling 'remote' instances
    
    # get our class type
    cls = getattr(sys.modules[__name__], params[0])  
    
    # create a new instance without invoking __init__
    instance = cls.__new__(cls)  
    
    # apply the passed state to the new instance
    instance.__dict__ = params[1]  
    
    # get the requested method
    method = getattr(instance, params[2])  
    args = params[3] if isinstance(params[3], (list, tuple)) else [params[3]]
    
    # expand arguments, call our method and return the result
    return method(*args)  

class CMultiProc(object):
    def __init__(self):
        self.val = None

    def calc(self, num,  i1, i2):
        self.num = num        
        val = 0        
        for i in range(i1, i2) :
                #val += math.cos(math.sqrt(i*i))
                val += i*i
        self.val = val
        return ( self.num, val )

    def do(self, data):
        t = Pool(processes=len(data))
        rs = t.map(parallelCall, self.prepareCall("calc", (data) ))
        t.close()
        return rs

    # creates a 'remote call' package for each argument
    def prepareCall(self, name, args):  
        for arg in args:
            yield [self.__class__.__name__, self.__dict__, name, arg]

if __name__ == "__main__":  # important protection for cross-platform use
    
    ############################################################################
    data = [ 
            (1,0       ,10000000), 
            (2,10000000,20000000), 
            (3,20000000,30000000), 
            (4,30000000,40000000), 
            (5,40000000,50000000),
            (6,50000000,60000000), 
            (7,60000000,70000000), 
            (8,70000000,80000000), 
            (9,80000000,90000000), 
            (10,90000000,100000000), 
            (11,100000000,110000000),
            (12,110000000,120000000),
            (13,120000000,130000000),
            (14,130000000,140000000),
            (15,140000000,150000000),
            (16,150000000,160000000),  
            ]
    ############################################################################
    # parallel    
    print("parallèle")
    t0 = time.time()
    multiProc = CMultiProc(  )    
    res =  multiProc.do( data  )
    vp = 0
    for num, val in res :
        vp += val
        print("% 5d % 5.1f " % (num, val) )
    print(vp)                
    pt = time.time()-t0           
    print("t=% 5.1f" % (pt),"s" )
    ############################################################################    
    # serial
    print("série")
    t0 = time.time()
    vs = 0
    for i in range(0,160000000) :
        # v += math.cos((math.sqrt(i*i)) )
        vs += i*i
    st = time.time()-t0
    print(vs)    
    print("t=% 5.1f" % (st),"s" )
    ############################################################################    
    # diff
    print("Diff", vp -vs )
    print("Gain", st / pt  )

Résultats:

parallèle
    1  333333283333335023616.0
    2  2333333183333335040000.0
    3  6333333083333335187456.0
    4  12333332983333334810624.0
    5  20333332883333336530944.0
    6  30333332783333336154112.0
    7  42333332683333335777280.0
    8  56333332583333331206144.0
    9  72333332483333330829312.0
   10  90333332383333334646784.0
   11  110333332283333334269952.0
   12  132333332183333329698816.0
   13  156333332083333337710592.0
   14  182333331983333341528064.0
   15  210333331883333324374016.0
   16  240333331783333319802880.0
1365333320533333360000000
t=  1.9 s
série
1365333320533333360000000
t= 12.0 s
Diff 0
Gain 6.214744302379906

19.2 Timer (onsolète voir multiprocessing)

import threading
prLock = threading.RLock()
# ...
        # initialization
        self.timer = None
        self.executing = False
        self.wating = False
# ...
    ############################################################################
    def doSomeThing(self):
        global prLock
        prLock.acquire()
        if self.executing:

            # ... do someThing in parallel thread

        prLock.release()
        self.launchTimer()
    ############################################################################
    def launchTimer(self):
        global prLock
        if self.executing:
            self.timer = threading.Timer(10, self.doSomeThing)
            self.timer.start()
        else:
            prLock.acquire()
            self.wating = False
            prLock.release()
# ...
    # start the main process
    prLock.acquire()
    param.wating = True
    param.executing = True
    prLock.release()

    # ... do things in the main thread

    prLock.acquire()
    param.executing = False

    print "wait ..."
    prLock.release()

    waiting = True
    while waiting:
        prLock.acquire()
        waiting = param.wating
        prLock.release()
    # the end of all

20 Aller plus loin avec le langage

20.1 Obtenir le nom ou les noms de la variable

tdo-1

A tester et valider :

def find_names(obj):
    frame = sys._getframe()
    for frame in iter(lambda: frame.f_back, None):
        frame.f_locals
    result = []
    for referrer in gc.get_referrers(obj):
        if isinstance(referrer, dict):
            for k, v in referrer.iteritems():
                if v is obj:
                    result.append(k)
    return result

20.2 Obtenir le nom de la fonction

20.2.1 Nom de fichier, n° de ligne, nom de fonction sur plusieurs niveaux

import sys
import inspect

def getFrameStr( fr  ):
    _, fileName = os.path.split( fr.f_code.co_filename )
    fname = fr.f_code.co_name
    line = fr.f_lineno
    return "%s(%d).%s" % (fileName,line,  fname)
 
def pfname():
    src1 = ""
    src2 = ""
    src3 = ""    
    nb = len(inspect.stack())
    print( nb )
    if nb > 2 :
        src1 = getFrameStr( sys._getframe(3) )
    if nb > 1 :    
        src2 = getFrameStr( sys._getframe(2) )
    if nb > 0 :    
        src3 = getFrameStr( sys._getframe(1) ) 
    print( "%s %s %s : " %(src1,src2,src3), end="" )

20.2.2 Fonction courante

def pfname( self ):
    print self.__class__.__name__,sys._getframe().f_code.co_name
def func_name():
    return sys._getframe(1).f_code.co_name

20.2.3 Fonction appelante

def pfname( self ):
    print self.__class__.__name__,sys._getframe(1).f_code.co_name

Voir aussi error_in_function


20.2.4 Liens

21 utilisation des feuilles excel

Working with Excel Files in Python

This site contains pointers to the best information available about working with Excel files in the Python programming language.
Documentation

22 clipboard - presse-papier

22.1 le module clipboard

import clipboard

clipboard.copy("abc")  # now the clipboard content will be string "abc"

text = clipboard.paste()  # text will have the content of clipboard

source  : https://pypi.python.org/pypi/clipboard/0.0.4

il faut aussi : https://pypi.python.org/pypi/pyperclip

22.2 Exemple d'application : copier le chemin du fond d'écran de gnome dans le clipboard

#!/bin/bash
the_bash_file=$0
the_bash_file_dir_name=$(realpath `dirname "$the_bash_file"`)
the_bash_file_base_name=`basename "$the_bash_file"`

imgpath=$(gsettings get org.gnome.desktop.background picture-uri)

python ${the_bash_file_dir_name}/toClipBoard.py "${imgpath}"


#!/bin/python
import os
import sys
import clipboard
clipboard.copy(sys.argv[1][1:-1])

23 Texte

23.1 Supprimer les accents

import unicodedata

def strip_accents(ss):
   s=ss
   return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')

23.2 rearrange_text

patWordSep=re.compile("\s+", re.DOTALL )
def rearrange_text( text, tab, rearrange_lf=0 ):
    lines = list()
    if rearrange_lf :
        txt = ''
        ww = text.split('\n')
        if len(ww) == 0 :
            txt = text
        else :
            for w in ww :
                txt += w.strip()+' '
        words = patWordSep.split( txt )
        if len(words) > 0 :
            txt = ""            
            line = ''
            for w in words :
                w=w.strip()
                if len(w) > 0 :
                    if len(line) + len(w) > 80 :
                        lines.append( line )
                        line = w + " "
                    else :
                        line=line+w+" "
            if len( line )>0 :
                lines.append( line )

    else :
        ww = text.split('\n')
        if len(ww) == 0 :
            lines.append( text )
        else :
            for w in ww :
                lines.append( w )

    txt = ''
    for line in lines :
        txt += tab+line+"\n"
    return txt

24 XML avec xml.dom.minidom

25 XML avec xml.sax.xmlreader

26 Tkinter : la bibliothèque graphique

27 Installation

27.1 Installation de librairies

27.1.1 Seulement pour un utilisateur

python setup.py install --user

27.2 Installation avec compilation des modules écrits en C

27.2.1 Sous WINDOWS

Le mieux est d'installer Visual Studio avec l'option « Python tools ... » en choisissant l'option « Installation personnalisée »

27.2.2 Sous Linux

28 pylint

pylint --generate-rcfile  > ~/.pylintrc

29 Annotation des functions - typage des arguments

Il est recommandé d'adopter les conventions suivantes pour améliorer la lisibilité du code :

def send_email(address,     # type: Union[str, List[str]]
               sender,      # type: str
               cc,          # type: Optional[List[str]]
               bcc,         # type: Optional[List[str]]
               subject='',
               body=None    # type: List[str]
               ):
    # type: (...) -> bool
    """Send an email message.  Return True if successful."""
    ...
from typing import List

class Example:
    def method(self,
               lst,      # type: List[str]
               opt=0,    # type: int
               *args,    # type: str
               **kwargs  # type: bool
               ):
        # type: (...) -> int
        """Docstring comes after type comment."""
        ...

30 PyHelp

31 Utilisation de python dans le monde du web (World Wide Web)

31.1 Apache/Python Integration (mod_python)

31.2 Apache/Python Integration (mod_wsgi)

31.3 |Apache/Python Integration Twited

31.4 Liens

32 Adaptateur Pyhton (wrapper, banding) pour d'autres langages - Bindings - Wrapping

33 mp3play

34 debuguer Python

35 Différences entre Python 2 et 3

36 Lines pour débuter

Par ordre de priorité décroissante :

37 Voir aussi

38 Liens

http://legacy.python.org/dev/peps/pep-3107/
http://khinsen.wordpress.com/
http://onclojure.com/2009/03/05/a-monad-tutorial-for-clojure-programmers-part-1/