# -*- coding: utf-8 -*- # others : cp1252 utf-8 from __future__ import division from __future__ import with_statement GlobalPVersion="4.182" """ abbréviation pour documentation : STR string NB nombre DT DateTime (Date et/ou Time) SY système IN Internet NE Réseau (local) PL PLUIE TST pour Tests DIV Divers PI Ponx interne PX Ponx """ """ try: import psyco psyco.full() except: pass """ import os import os.path import sys import traceback #import atexit import locale import string import cStringIO import cPickle import re import socket import urllib import urllib2 import urlparse import ftplib import time import datetime import htmllib import htmlentitydefs import nntplib import formatter import quopri import binascii import codecs import zipfile import zlib import email,email.Header,email.mime.image,email.mime.text import threading,Queue import win32pipe,win32clipboard,win32con,win32gui,win32api import win32com.client import pythoncom,pywintypes,winerror,types from win32com.server.exception import COMException ###import win32ui import ctypes #from win32com.client import Dispatch #from poplib import * #import poplib, smtplib, MimeWriter, mimetypes, base64, tempfile #Python 2.5 import poplib, smtplib, mimetypes, base64, tempfile def initponxdir(): """retourne le directory de Ponx Si besoin, ajoute à la volée dans PYTHONPATH """ #return(os.path.dirname(__file__)) import _winreg try: kkk = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Classes\CLSID\{EC501258-201C-449C-BE20-837A316EA382}\PythonCOMPath') name, value, type = _winreg.EnumValue(kkk, 0) if not sys.path.__contains__(value): sys.path.append(value) return(value) except: return('') GlobalPonxDir = initponxdir() #if not os.path.isfile(os.path.dirname(__file__)+'\\pglobal.py'): if not os.path.isfile(GlobalPonxDir+'\\pglobal.py'): f=open(GlobalPonxDir+'\\pglobal.py','w') f.write("GlobalSource = None\r\n") f.close() import pglobal #pglobal.GlobalU="AZéèE123" #print pglobal.GlobalU #pglobal.lsignal=['pglobal.lsignal'] if os.path.isfile(GlobalPonxDir+'\\pxperso.py'): import pxperso class defvpublic(object): Count=0 def _init_(self): self.__class__.Count += 1 pass vpublic=defvpublic() import pasram try: outencodage=pasram.outencodage except: outencodage='utf-8' import pdebug import dico DFORM=dico.dico() UI=dico.dico() GlobalIdSession=str(time.time())[-7:] GlobalTacheID=[None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None] CRLF = '\r\n' nfichier='.RETURNSTRING.' chaineretour='' GlobalCONTROL='' CodingParDefaut=locale.getpreferredencoding() GlobalObject=None GlobalGenerator1=None GlobalGenerator2=None GlobalAppel='' GlobalReponse='' GlobalPARAM=[] GlobalPARAMliste=[] GlobalPARAMUI=[] GlobalSignal=['PONX_INIT'] UItlien={} UItnum=[] GlobalPARAMindexRetour=0 GlobalMMAP={} SEPARITEMSERIAL='\t' SEPARLIGSERIAL='\n' SEPARLIGSERIAL=chr(255) Global_fcalcRE=None GlobalRGEX=None GlobalOptions=[] GlobalWscript=None Omodul={} persist_dict={} TCPconnexion = None TCPHOST=None TCPPORT=22222 newsserver='' newsport=119 newsuser='' newspasse='' groupname='' pdestination='' newspremier='' newsdernier='' autoitprefix="simili-com-serveur-bridge-autoit-1" hautoitmessage=None Gcherrywrite='' Gcherryread={} Gcherrytemplate={} Gcherrysession=None Gcherrycontent={} Gcherryindex={} """ try: import pylab #pylab.use('TK') #import pylab except: print('Problem','with matplotlib') pass sys.exit() """ try: from ponxmsg import _,set_ except: def _(msg): return msg tqp_taskwait=Queue.Queue() tqp_taskcours=Queue.Queue() tqp_result=Queue.Queue() tqp2_taskwait=Queue.Queue() tqp2_taskcours=Queue.Queue() tqp2_result=Queue.Queue() tqp_2=0 ponx_thread=[] ponx_thread2=[] tq_ftp=Queue.Queue() tq_ftpnb=0 tq_nb=0 tq_tai=0 # PX def vifi(*args): """Visualise une chaine ; affiche un message. L'architecture de PONX fait que le message sera récupéré par l'appelant, à la fin du l'appel. """ global chaineretour,CRLF if outencodage=='utf-8': for chaine in args: try: vpublic.ponxvvifi=chaine except: pass chaineretour=chaineretour+chaine+'\n' else: for chaine in args: try: chaineretour=chaineretour+chaine.decode('utf-8').encode('cp1252','replace')+'\n' except: chaineretour=chaineretour+chaine+'\n' try: vpublic.ponxvvifi=chaine except: pass """ global nfichier,fichier,chaineretour,CRLF if nfichier== '.NONE.': for chaine in args: print(chaine), elif nfichier=='.RETURNSTRING.': if outencodage=='utf-8': for chaine in args: chaineretour=chaineretour+chaine+'\n' else: for chaine in args: chaineretour=chaineretour+chaine.decode('utf-8').encode('cp1252','replace')+'\n' else: for chaine in args: fichier.write(chaine.decode('utf-8').encode('cp1252','replace')) """ #*** 4.11.05 v2.46 *** # PX def consoleprint(txt): print txt #*** 4.11.05 v2.46 *** # PX def consoleprintgpl0(): print ''.join(GlobalPARAMliste) #*** 4.11.05 v2.46 *** # PX def consoleprintgpl1(): print '\r\n'.join(GlobalPARAMliste) #*** 17.7.05 v2.35 *** # PX def vilist(*args): global chaineretour for a in args: try: if type(a) is unicode: chaineretour+=u1252(a) else: try: chaineretour+=str(a) except: chaineretour+=repr(a) except: chaineretour+=' ' chaineretour+=SEPARITEMSERIAL chaineretour+=SEPARLIGSERIAL # PX def printlist(l): for item in l: print item #***NEW 13.06.05 *** # PX def rout(*args): """Retourne les arguments accolés, supposés en utf-8, avec conversion en cp1252 """ sret='' for item in args: if outencodage=='utf-8': sret=sret+item else: sret=sret+str(item).decode('utf-8').encode('cp1252','replace') return sret # PX def retourne(valeu): """affecte à chaineretour une valeur """ global chaineretour chaineretour=valeu #*** 2.99 *** # PX def GlobalPAR(num=0): """à compléter """ return GlobalPARAM[num] # OLD def ponxquit(): """Plus utilisé ; sauf si l'on utilise le passage de paramètres par fichier. """ global nfichier,fichier if nfichier!= '.RETURNSTRING.': fichier.close() # OLD def ponxopen(dossier): """Plus utilisé ; sauf si l'on utilise le passage de paramètres par fichier. Le fichier sortant est nommé "Ponx.out", dans le répertoire indiqué par le paramètre "dossier". """ global nfichier,fichier,chaineretour nfichier=dossier if dossier=='.RETURNSTRING.': chaineretour='' else: fichier=open(nfichier+'\\ponx.out','w') # PX def ponxsysinfo(): """Retourne une chaine, contenant plusieurs caractéristiques de l'ordinateur, et de Ponx. """ global chaineretour import socket lver=[] def ajout(libel=None,valeur=None): global chaineretour lver.append([libel,str(valeur)]) ajout('Ponx version',GlobalPVersion) ajout() ajout('Ponx directory',ponxdir()) try: langue=pasram.langue ajout("Ponx's langage",pasram.langue) except: ajout("Pasram.py introuvable :","problème") ajout() ajout('Name station',socket.gethostname()) ajout('IP station',socket.gethostbyname(socket.gethostname())) ajout() #ajout('Python version',sys.version) ajout('Python win version',sys.winver) #ajout('',sys.copyright) ajout('platform',sys.platform) ajout('windows version',sys.getwindowsversion()) #ajout('',sys.dllhandle) #ajout('',sys.exc_info()) ajout('Python defaultencoding',sys.getdefaultencoding()) ajout('system encoding',sys.getfilesystemencoding()) ajout('recursion limite',sys.getrecursionlimit()) #ajout('hex version',sys.hexversion) ajout('maxint',sys.maxint) ajout('maxunicode',sys.maxunicode) #ajout('path',sys.path) ajout('prefix',sys.prefix) #ajout('api version',sys.api_version) #import platform #print platform.architecture() #print platform.node() #print platform.platform() #print platform.release() #print platform.system() #print platform.version() #print platform.win32_ver() chaineretour='' for item in lver: if item[0] is None: chaineretour+='\r\n' else: chaineretour=chaineretour+'\r\n'+item[0]+' : '+item[1] return lver #*** 4.1.06 v3.08 *** # IN NE def iip(): url='http://www.monip.org' try: page = urllib.urlopen(url).read() i = string.find(page, 'IP : ')+5 j = string.find(page, '21: clef=st[-2:] reste=eval(st+'%97') if reste==0: return True else: return False # DIV def ribclef(*rib): """Calcule la clef d'un RIB (Releve Identite Bancaire francais) exemple: print ribclef("300040140400061661669") print ribclef("30004014040006166166910") print ribclef("30004","0140400061661669","10") """ st=''.join(rib) st=st.upper() st=remplacerchxpar(st, *(' ,,A,1,B,2,C,3,D,4,E,5,F,6,G,7,H,8,I,8,J,1,K,2,L,3,M,4,N,5,O,6,P,7,Q,8,R,9,S,2,T,3,U,4,V,5,W,6,X,7,Y,8,Z,9'.split(','))) if len(st)>21: st=st[:21]+'00' else: st=st+"0"*(23-len(st)) clef=97-eval(st+'%97') return ("100"+str(clef))[-2:] # DIV def nsstest(*num): """Test si la clef d'un N°INSEE (n°SS) est valide exemple: print nsstest("155030702300344") print nsstest("1550307023003","44") print nsstest("1 55 03 07 023 003","44") """ nss=''.join(num) st=remplacerchxpar(nss, ' ','','A','0','B','0') sex=st[0] mois=st[3:4] if len(st)>13: clef=st[-2:] else: clef='' st=st[:13] if nss.find('A')>-1: nb=int(st)-1000000 elif nss.find('B')>-1: nb=int(st)-2000000 else: nb=int(st) reste=97-nb%97 if str(reste)==clef: return True else: return False # DIV def nssclef(*num): """Calcule la clef d'un N°INSEE (n°SS) exemple: print nssclef("155030702300344") print nssclef("1550307023003") print nssclef("1 55 03 07 023 003") """ nss=''.join(num) st=remplacerchxpar(nss, ' ','','A','0','B','0') sex=st[0] mois=st[3:4] st=st[:13] if nss.find('A')>-1: nb=int(st)-1000000 elif nss.find('B')>-1: nb=int(st)-2000000 else: nb=int(st) clef=97-nb%97 return ("100"+str(clef))[-2:] # DIV def pgdc(a,b): """Retourne le PGDC (Plus Grand Dénominateur Commun) de deux nombres entiers """ u, u1 = 1, 0 v, v1 = 0, 1 while b: q = a // b u, u1 = u1, u - q * u1 v, v1 = v1, v - q * v1 a, b = b, a - q * b return a # DT def age(date1=datetime.date(2008,04,29), date2=datetime.date(2008,01,01)): """Retourne l'age de date2 par rapport à date1 Tiens compte des dates d'anniversaire. """ age=date2.year-date1.year if date2.month 2008-04-08 Suggestion pour format : print dat.strftime('%a %d-%m-%Y') print dat.strftime('%d-%m-%y') print dat.strftime('%d/%m/%Y') """ locale.getlocale() # (None, None) locale.setlocale(locale.LC_ALL, "") # FrenchçFrance dp=datetime.date.fromordinal(n-118) return dp # DT def datetopdox(dat): """retourne un number (compatible Paradox) à partir d'un datetime.date exemple : dat=datetopdox(datetime.date(2009,1,1)) #==> 733526 """ locale.getlocale() # (None, None) locale.setlocale(locale.LC_ALL, "") # FrenchçFrance np=datetime.date.toordinal(dat)+118 return np # DT def datetimefrompdox(ns): """retourne datetime.datetime, à partir d'un number (d'origine Paradox) exemple : dat=datetimefrompdox(63344628492000) #==> mer. 23-04-2008 10:08:12 Suggestion pour format : print dt.strftime('%a %d-%m-%Y %H:%M:%S') print dt.strftime('%d-%m-%y %H:%M:%S') print dt.strftime('%H:%M:%S, %d.%m.%Y') # à la Paradox """ locale.getlocale() # (None, None) locale.setlocale(locale.LC_ALL, "") # FrenchçFrance n = ns/1000 dat,tim=divmod(n,3600*24) h,m=divmod(tim,3600) m,s=divmod(m,60) t,ms=divmod(ns,1000) ptim=datetime.time(h,m,s,ms*1000) pdat=datetime.date.fromordinal(dat) pdatim=datetime.datetime.combine(pdat,ptim) return pdatim # DT def datetimetopdox(datim): """retourne un number (compatible Paradox) à partir d'un datetime.datetime exemple : dt=datetime.datetime(2008,4,23,10,8,12,1000) dat=datetimetopdox(dt) #==> 63344628492001 """ locale.getlocale() # (None, None) locale.setlocale(locale.LC_ALL, "") # FrenchçFrance nbpx = datetime.date.toordinal(datim.date())*3600*24 t=datim.time() nbpx += t.hour*3600 + t.minute*60 + t.second nbpx = nbpx*1000 + t.microsecond/1000 return nbpx #return pdatim # STR NB def trad(nb, unite='euro', decim='centime'): """ Traduction de sommes en lettres. Exemples : print 12.30,trad(12.30,'heure','minute') print 12.03,trad(12.03,'heure','minute') print 12.30,trad(12.30,'heure','') print 1.8,trad(1.8,'mètre','') print 2.5,trad(2.5,'litre','') print 3.5,trad(3.5,decim='') print 300,trad(300) print 301,trad(301) print 1000,trad(1000) print 1001,trad(1001) print 1400,trad(1400) print 1401,trad(1401) print 0,trad(0) print -650.92,trad(-650.92) """ def tradd(num): ch='' if num==0 : ch='' elif num<20: ch=t1[num] elif num>=20: if (num>=70 and num<=79)or(num>=90): z=int(num/10)-1 else: z=int(num/10) ch=t2[z] num=num-z*10 if (num==1 or num==11) and z<8: ch=ch+' et' if num>0: ch=ch+' '+tradd(num) else: ch=ch+tradd(num) return ch def tradn(num): ch='' flagcent=False if num>=1000000000: z=int(num/1000000000) ch=ch+tradn(z)+' milliard' if z>1: ch=ch+'s' num=num-z*1000000000 if num>=1000000: z=int(num/1000000) ch=ch+tradn(z)+' million' if z>1: ch=ch+'s' num=num-z*1000000 if num>=1000: if num>=100000: z=int(num/100000) if z>1: ch=ch+' '+tradd(z) ch=ch+' cent' flagcent=True num=num-z*100000 if int(num/1000)==0 and z>1: ch=ch+'s' if num>=1000: z=int(num/1000) if (z==1 and flagcent) or z>1: ch=ch+' '+tradd(z) num=num-z*1000 ch=ch+' mille' if num>=100: z=int(num/100) if z>1: ch=ch+' '+tradd(z) ch=ch+" cent" num=num-z*100 if num==0 and z>1: ch=ch+'s' if num>0: ch=ch+" "+tradd(num) return ch if isinstance(nb, (basestring,unicode)): nb=decodenumber(nb) nb=round(nb,2) t1=["","un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf"] t2=["","dix","vingt","trente","quarante","cinquante","soixante","septante","quatre-vingt","nonante"] t2=["","dix","vingt","trente","quarante","cinquante","soixante","soixante-dix","quatre-vingt","quatre-vingt-dix"] z1=int(nb) z3=abs((nb-z1)*100) z2=int(round(z3,0)) if z1==0: ch="zéro" else: ch=tradn(abs(z1)) if z1>1 or z1<-1: if unite!='': ch=ch+" "+unite+'s' else: ch=ch+" "+unite if abs(z2)>0.005: ch=ch+tradn(z2) if z2>1 or z2<-1: if decim!='': ch=ch+" "+decim+'s' else: ch=ch+" "+decim if nb<0: ch=" moins"+ch return ch def aplati2(l): """ aplati une liste de listes, quelque soit le le niveau d'imbrication exemple: print list(aplati([1,2,[3,[4,'quatre','QUATRE']],5,6])) >>> [1, 2, 3, 4, 'quatre', 'QUATRE', 5, 6] """ for item in l: if isinstance( item, types.ListType): for iii in aplati( item): yield iii else: yield item def aplati(l): """ aplati une liste de listes, quelque soit le le niveau d'imbrication exemple: print list(aplati([1,2,[3,[4,'quatre','QUATRE']],5,6])) >>> [1, 2, 3, 4, 'quatre', 'QUATRE', 5, 6] """ for item in l: if hasattr(item, '__iter__'): for iii in aplati(item): yield iii else: yield item #***NEW*** from UserDict import IterableUserDict as UserDict from UserList import UserList # DIV class dico(UserDict): """dictionnaire avec conservation de l'ordre de création""" def __init__(self, dict = None): self._keys = [] UserDict.__init__(self, dict) def __delitem__(self, key): UserDict.__delitem__(self, key) self._keys.remove(key) def __setitem__(self, key, item): UserDict.__setitem__(self, key, item) if key not in self._keys: self._keys.append(key) def clear(self): UserDict.clear(self) self._keys = [] def copy(self): dict = UserDict.copy(self) dict._keys = self._keys[:] return dict def items(self): return zip(self._keys, self.values()) def keys(self): return self._keys def popitem(self): try: key = self._keys[-1] except IndexError: raise KeyError('dictionary is empty') val = self[key] del self[key] return (key, val) def setdefault(self, key, failobj = None): UserDict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) def update(self, dict): UserDict.update(self, dict) for key in dict.keys(): if key not in self._keys: self._keys.append(key) def values(self): return map(self.get, self._keys) def valord(self, num): return self[self._keys[num]] """Un 'tablet' est un ensemble, non structuré, de lignes,d dans lequel chaque ligne est caractérisée par une clef (string), et un 'irecord' Un 'irecord' est un liste de champs (field) Attn : un irecord contient des champs, et non la valeur de ces champs. (A) Un 'champ' (field) est composé de - un nom (name) - une valeur d'origine 'vieille' (valold) - une valeur courante (value) Un tablet peut contenir des irecord hétéroclites. C'est la struture du irecord qui est utilisée pour savoir quelles sont les données à lire/écrire. Se tromper de irecord provoquer une erreur d'éxécution. (A) par exemple : codarticle=field("CODART",'AZERTY') prixunitaire=field("PXU",12.34) artvendu=irecord(codarticle, prixunitaire) On n'utilisera pas artvendu.codarticle, ou artvendu["codarticle"], mais codarticle.value, tout simplement. A noter que artvendu[0].value est équivalent. (B) Malgré ça, il possible de simuler la structure d'une table, via un irecord. Cela permettra, notamment, une séparation en XML """ # DIV def preparstring(chaine,mode): """ effectue plusieurs mises en forme, selon le mode : - 'sql' : remplace ' par '' et chaine_vide par "NULL" - 'sqlnull' : remplace '' par "NULL" - 'pdox' ou 'pdx' : remplace " par \" @param chaine: chaine à traiter @param mode: le genre de traitement à faire @return: chaine modifiée Exemples:: zzzz eezezeezzer ezeez """ if mode=='sql': chi=re.sub("'", "''", str(chaine)) if chi=='': return "NULL" else: return "'"+chi+"'" if mode=='sqlnull': return re.sub("''", "NULL", str(chaine)) if mode=='pdox' or mode=='pdx': return re.sub('"', r'\"', str(chaine)) #***NEW*** def isfield(item): """@return :retourne True si item est un field, sinon False """ try: if item.__class__==field: return True else: return False except: return False #***NEW*** class field(object): """Objet champ (field) des Tablets. """ def __init__(self, nom, valeur=None, valold=None): self.name=nom self.value=valeur if (valold is None) and not(valeur is None): self.valold=valeur else: self.valold=valold def sqmodif(self): supdate="" swhere="" if self.value!=self.valold: supdate=self.name+"="+preparstring(self.value,'sql')+", " swhere="("+self.name+"="+preparstring(self.valold,'sql')+") AND " return supdate,swhere #***NEW*** class irecord(UserList): """irecord est un groupe de champs """ def __init__(self, *args): """ @param *args: liste des champs """ self.data=[] for item in args: self.data.append(item) def __add__(self, args): """ajoute des champs à un irecord """ for item in args: self.data.append(item) def lnames(self): """@return : retourne la liste des noms de champs irecord """ lret=[] for champ in self.data: lret.append(champ.name) return lret def lvalue(self): """@return : retourne la liste des valeurs des champs du irecord """ lret=[] for champ in self.data: lret.append(champ.value) return lret def wvalue(self, lst): """Affecte une liste de valeurs aux champs du irecord @sample : rec=irecord(cha,chb,chc) rec.wvalue(1,2,3) rec.lvalue(): [1,2,3] @return :le irecord, afin de pouvoir enchaîner les fonctions """ for champ,valeur in zip(self.data,lst): champ.value=valeur return self def wavalue(self, *args): """Affecte une liste de valeurs-'arguments' aux champs du irecord @sample : rec=irecord(cha,chb,chc) rec.wavalue(11,22,33) rec.lvalue(): [11,22,33] @return :le irecord, afin de pouvoir enchaîner les fonctions """ for champ,valeur in zip(self.data,args): champ.value=valeur return self def lvalold(self): """@return : retourne la liste des valeurs anciennes des champs du irecord """ lret=[] for champ in self.data: lret.append(champ.valold) return lret def lmodif(self): """@return : retourne la liste des n° champs de irecord qui ont été modifiés """ lret=[] n=0 for champ in self.data: n+=1 if champ.value!=champ.valold: lret.append(n) return lret def restold(self): """réaffecte les valeurs old aux valeurs courantes """ n=0 for champ in self.data: if champ.value!=champ.valold: champ.value=champ.valold n+=1 def restold(self): """réaffecte les valeurs old aux valeurs courantes """ n=0 for champ in self.data: if champ.value!=champ.valold: champ.value=champ.valold n+=1 def setnone(self): """affecte les valeurs à None """ for champ in self.data: champ.value=None def pmodif(self): """@return : retourne la liste des champs (pointeurs) de irecord qui ont été modifiés """ lret=[] for champ in self.data: if champ.value!=champ.valold: lret.append(champ) return lret def sqmodif(self): """@return : retourne la requête Sql-source de màj des champs modifiés de irecord """ supdate="""UPDATE TABLE \r\n SET""" swhere="WHERE " for champ in self.data: """ if champ.value!=champ.valold: supdate+=champ.name+"='"+str(champ.value)+"', " swhere+="("+champ.name+"='"+str(champ.valold)+"') AND " """ if champ.value!=champ.valold: su,sw=champ.sqmodif() supdate+=su swhere+=sw return supdate[:-2]+"\r\n "+swhere[:-5] def lidentiq(self): """@ret : retourne la liste des n° champs de irecord qui n'ont pas été modifiés """ lret=[] n=0 for champ in self.data: n+=1 if champ.value==champ.valold: lret.append(n) return lret def pidentiq(self): """@return : retourne la liste des champs (pointeurs) de irecord qui n'ont pas été modifiés """ lret=[] for champ in self.data: if champ.value==champ.valold: lret.append(champ) return lret def tabletread(self, tablet, clef): """charge (lit) le irecord depuis une ligne d'une itablet @return :le irecord, afin de pouvoir enchaîner les fonctions @sample : print rec.tableread(ttst,66).lvalue() """ tablet.recread(clef, self) return self def tabletwrite(self, tablet, clef): """écrit le irecord dans une ligne d'une itablet @return :le irecord, afin de pouvoir enchaîner les fonctions """ tablet.recwrite(clef, self) return self #***NEW*** class itablet(UserDict): """itablet est un groupe de records """ def __init__(self): self.data={} def write(self, clef, lst): """ajoute des champs à un irecord """ self.data[clef]=lst def read(self, clef): """@return : retourne la liste des valeurs des champs du irecord """ return self.data[clef] def delete(self, *args): """supprime (delete) une ligne @return : nb de suppressions effectuées """ n=0 for clef in args: try: del(self.data[clef]) n+=1 except: pass def recwrite(self, clef, rec): """ajoute un irecord """ self.data[clef]=rec.lvalue() def recread(self, clef, rec): """@return : lit un irecord """ if self.data.has_key(clef): rec.wvalue(self.data[clef]) else: rec.setnone() def persistwrite(self,nomfichier): try: import shelve tmp=shelve.open(nomfichier) tmp["1"]=self.data tmp.close() return True except: return False def persistread(self,nomfichier): try: import shelve tmp=shelve.open(nomfichier) self.data=tmp["1"] tmp.close() return True except: return False # 3.14 def visutout(self): for clef in self.data: print clef, self.data[clef] # 3.14 def CreModSup(self, tablet): cre=[] mod=[] sup=[] for clef in self.data: if tablet.has_key(clef): if self.data[clef]!=tablet.data[clef]: mod.append(clef) else: cre.append(clef) for clef in tablet.data: if self.has_key(clef): #modif pass else: sup.append(clef) return cre,mod,sup # 3.14 def CreModSupData(self, tablet): cre=itablet() mod=itablet() sup=[] for clef in self.data: if tablet.has_key(clef): if self.data[clef]!=tablet.data[clef]: mod.data[clef]=self.data[clef] else: cre.data[clef]=self.data[clef] for clef in tablet.data: if self.has_key(clef): #modif pass else: sup.append(clef) return cre,mod,sup # NB STR def decodenumber(st,decimal="."): """Extrait un nombre décimal, à partir d'une chaîne de caractères. Cela est fait d'une manière souple.""" vret=''.join([mappingcharnumber.get(i, i) for i in st]) vret=vret.replace(',',decimal) return vret.replace('.',decimal) # NB STR def decodeinteger(st): """Extrait un nombre entier (purement numérique), à partir d'une chaîne de caractères. Cela est fait d'une manière souple. Exemple : "12-34/56.78|9O" donnera "1234567890" les caractères non numériques sont supprimés les caractères ressemblants sont remplacés par leur équivalent numérique exemples: O => 0 I => 1 l => 1 ce qui permet de corriger des erreurs de saisie. """ return ''.join([mappingcharinteger.get(i, i) for i in st]) # NB STR def forcefloat(st): """Retourne un nombre flottant, d'après une chaîne ; cela est fait d'une manière souple.""" signe=1.0 if st.startswith('-'): signe=-1.0 st=st[1:] num=decodenumber(st) vret=signe*float(num) return vret # NB STR def forceint(st): """Retourne un nombre entier, d'après une chaîne ; cela est fait d'une manière souple.""" try: vret=int(decodenumber(st)) except: vret=0 return vret # DT STR def decodedate(st): """Extrait une date, à partir d'une chaîne de caractères. Cela est fait d'une manière souple.""" st=string.strip(st) st=string.replace(st,' ','.') st=''.join([mappingcharnumber.get(i, i) for i in st]) if len(st)<5: a=datetime.date.today().year if len(st)<3: m=datetime.date.today().month j=int(st) else: jm=st if len(jm)==4: j=int(jm[:2]) m=int(jm[-2:]) else: m=int(jm[-2:]) if m>12: j=int(jm[:2]) m=int(jm[-1:]) else: j=int(jm[:1]) else: if string.find(st,'.')>0: try: j,m,a=string.split(st,'.') j,m,a=int(j),int(m),int(a) except: j,m,a=0,0,0 else: if len(st)>6: a=int(st[-4:]) jm=st[:-4] else: a=int(st[-2:]) jm=st[:-2] if len(jm)==4: j=int(jm[:2]) m=int(jm[-2:]) elif len(jm)==2: j=int(jm[:1]) m=int(jm[-1:]) else: m=int(jm[-2:]) if m>12: j=int(jm[:2]) m=int(jm[-1:]) else: j=int(jm[:1]) if a<100: if a<30: a=2000+a else: a=1900+a return datetime.date(a,m,j) # DT STR def decodetime(st): """Extrait un time, à partir d'une chaîne de caractères. Cela est fait d'une manière souple.""" # a hour m minute j second st=string.strip(st) st=string.replace(st,' ','.') st=string.replace(st,':','.') st=string.replace(st,',','.') st=string.replace(st,'/','.') st=string.replace(st,'-','.') st=''.join([mappingcharnumber.get(i, i) for i in st]) if len(st)<=5: j = time.localtime()[5] if len(st)<3: m = time.localtime()[4] a = int(st) else: am = st if len(am)>=4: a=int(am[:2]) m=int(am[-2:]) else: m=int(am[-2:]) if m>59: a=int(am[:2]) m=int(am[-1:]) else: a=int(am[:1]) else: if string.find(st,'.')>0: try: a,m,j=string.split(st,'.') a,m,j=int(a),int(m),int(j) except: a,m,j=0,0,0 else: j=int(st[-2:]) am=st[:-2] if len(am)==4: a=int(am[:2]) m=int(am[-2:]) elif len(am)==2: a=int(am[:1]) m=int(am[-1:]) else: m=int(am[-2:]) if m>60: a=int(am[:2]) m=int(am[-1:]) else: a=int(am[:1]) return datetime.time(a,m,j) # DT STR def decodedatetime(st): """Extrait un datetime, à partir d'une chaîne de caractères. Cela est fait d'une manière souple. La séparation entre date et time doit être un espace en retour, on a (date,time) """ s=st.strip() l=len(s) i=s.find(' ') while i<(l/2): i=s.find(' ') d=st[:i] t=st[i+1:] return decodedate(d),decodetime(t) """ ordre='0123456789' #numérique simple ordre='0123456789abcdef' #hexadécimal ordre='ABCDEFGHIJKLMNOPQRSTUVWXYZ' #alphabétique majuscule ordre='abcdefghijklmnopqrstuvwxyz' #alphabétique minuscule ordre='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' #alphanumérique-1 majuscule ordre='abcdefghijklmnopqrstuvwxyz0123456789' #alphanumérique-1 minuscule ordre='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' #alphanumérique-2 majuscule ordre='0123456789abcdefghijklmnopqrstuvwxyz' #alphanumérique-2 minuscule ordre='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' #alphanumérique-1 complet ordre='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' #alphanumérique-2 complet ordre='0123456789abcdefghijklmnopqrstuvwxyz' #répétition """ # PI def alphanumsuit(a, b, ordre): """ Usage interne ; appelé par alphanumsuite """ d,f=a[0],b[0] listret=[] num=0 for i in range(ordre.find(d),ordre.find(f)+1): num+=1 if len(a)>1: deb,fin=a[1:],b[1:] if i>ordre.find(d): deb[0]=ordre[0] if i<(ordre.find(f)): fin[0]=ordre[-1] for s in alphanumsuit(deb,fin, ordre): listret.append(ordre[i]+s) else: listret.append(ordre[i]) return listret # DIV STR # ACF alphanumsuite('image12.jpg', 'image22.jpg','0123456789') def alphanumsuite(a,b, ordre='0123456789abcdefghijklmnopqrstuvwxyz'): """ Retourne une liste de chaînes, pour un intervalle. exemples : alphanumsuite('abc7.jpg', 'abcb.jpg', ordre='0123456789abcdefghijklmnopqrstuvwxyz') alphanumsuite('abc8.jpg', 'abc012.jpg') """ na,nb=len(a),len(b) suffix='' for i,j in zip(a[::-1],b[::-1]): if i!=j: break na-=1 nb-=1 suffix=i+suffix pa,pb=0,0 prefix='' for i,j in zip(a[::1],b[::1]): if i!=j: break pa+=1 pb+=1 prefix+=i l=len(a[pa:na])-len(b[pa:nb]) filla=fillb=[] if l>0: fillb=list(ordre[-1]*l) if l<0: filla=list(ordre[0]*(-l)) r=alphanumsuit( filla+(list(a[pa:na])), fillb+(list(b[pa:nb])), ordre) return [prefix+i+suffix for i in r] # DIV STR def alphanumsuitetab(a,b, ordre='0123456789abcdefghijklmnopqrstuvwxyz'): """ Version 'tabulaire' de alphanumsuite. La liste retournée est une (grande) chaine, avec les éléments séparés par des Tab (\t) """ return '\t'.join(alphanumsuite(a,b, ordre)) def calendrierhtml(annee,mois,taille='60%',cadre='OUI'): """ Crée un tableau en HTML (compatible THE) du calendrier d'un mois retourne le HTML """ import calendar,locale locale.getlocale() # (None, None) locale.setlocale(locale.LC_ALL, "") # FrenchçFrance calendar.setfirstweekday(calendar.MONDAY) # semaine commençant le lundi tmpcadre = 'border-collapse: collapse; border-style: solid; border-width: 1px; border-color: #cccccc;' tdstyle = ' style="border-style: solid; border-width: 1px; border-color: #cccccc; BACKGROUND-COLOR: #ffffff;"' if cadre.upper() !='OUI': tmpcadre = 'border-style: none' tdstyle = ' style="BACKGROUND-COLOR: #ffffff;"' titre='

'+str(annee)+'.'+str(mois)+'
' tableau = titre+'' tableau += ''; tableau += '

Lu

' tableau += '

Ma

' tableau += '

Me

' tableau += '

Je

' tableau += '

Ve

' tableau += '

Sa

' tableau += '

Di

' tableau += '
'; for w in calendar.monthcalendar(annee,mois): tableau += ''; for j in w: tableau += '

' if j>0: tableau += str(j) tableau += '

' tableau += '
' tableau += '

'; return tableau # PI def ficfilter(lst, patterns): """ Utilisé par aldirdetail Retourne deux sous-listes de la liste-fichiers LST : - la première est la liste qui respecte la liste PATTERNS - la deuxième est la liste qui ne respecte pas la liste PATTERNS filter remplace fnmatch, car sous Windows fnmatch se plante avec '*.*' et les fichiers '*.' """ result=[] antiresult=[] for pattern in patterns: patroot,patext=os.path.splitext(pattern) patroot=string.upper(patroot) patext=string.upper(patext) for item in lst: tmproot,tmpext=os.path.splitext(item[0]) tmproot=string.upper(tmproot) tmpext=string.upper(tmpext) if (tmproot==patroot or patroot=="*") and (tmpext==patext or patext==".*") : result.append(item) for item in lst: if not item in result: antiresult.append(item) result.sort() antiresult.sort() return(result,antiresult) def ficseri2(lst): """ Utilisé par aldirdetail """ sret="" for lig in lst: sret=sret+lig[0]+'\t'+time.strftime("%H:%M:%S, %d.%m.%y",time.gmtime(lig[1]))+'\t'+str(lig[2])+chr(255) return sret #***MODIF 27.06.06 v3.213 *** doubleretour def aldirdetail(rep,patterns=['*.*'],tretour='LISTE'): """Liste des fichiers d'un répertoire, avec détails : date-heure + taille @param tretour: 'LISTE' ou 'ANTI' ou 'DIR' """ global chaineretour lf=[] rp=[] for i in os.listdir(rep): #print unicode(rep+'\\')+unicode(i) try: if not os.path.isdir(unicode(rep+'\\')+unicode(i)): st=os.stat(unicode(rep+'\\')+unicode(i)) lf.append((i,st[8],st[6])) else: rp.append(i) except: pass lst,anti=ficfilter(lf,patterns) if tretour=="ANTI": chaineretour=ficseri2(anti) vret=ficseri2(anti) elif tretour=="DIR": chaineretour=ficseri2(rp) vret=ficseri2(rp) else: chaineretour=ficseri2(lst) vret=ficseri2(lst) return vret #*** MODIF:29.11.05 ; return *** def aldir(rep,patterns=['*.*'],tretour='LISTE'): """Liste des fichiers d'un répertoire, sans détail @param tretour: 'LISTE' ou 'ANTI' ou 'DIR' """ global chaineretour import zipmci lf=[] rp=[] for i in os.listdir(rep): if not os.path.isdir(rep+'\\'+i): lf.append(i) else: rp.append(i) lst,anti=zipmci.pfilter(lf,patterns) if tretour=="ANTI": chaineretour=string.join(anti,'\t') lret=anti elif tretour=="DIR": chaineretour=string.join(rp,'\t') lret=rp else: chaineretour=string.join(lst,'\t') lret=lst return lret #*** new: 3.252 *** def aldira(rep,patterns='*.*',tretour='LISTE'): """Liste des fichiers d'un répertoire, sans détail @param tretour: 'LISTE' ou 'ANTI' ou 'DIR' """ global chaineretour import zipmci lf=[] rp=[] for i in os.listdir(rep): if not os.path.isdir(rep+'\\'+i): lf.append(i) else: rp.append(i) if type(patterns) in (types.ListType,types.TupleType): lst,anti=zipmci.pfilter(lf,patterns) else: lst,anti=zipmci.pfilter(lf,[patterns]) if tretour=="ANTI": return anti #chaineretour=string.join(anti,'\t') elif tretour=="DIR": return rp #chaineretour=string.join(rp,'\t') else: return lst #chaineretour=string.join(lst,'\t') #***new: 3.215 ; 18.07.2006 *** def aldirre(rep,pattern=r"^.+", casse="NON",tretour='LISTE'): """ Liste des fichiers d'un répertoire, filtré avec re Filtre les fichiers, par une expression relationnelle, appliquée aux noms de le liste des fichiers Attn : la casse est ignorée par défaut. @param pattern: l'expression relationnelle ; le "motif" (pattern) @param casse: casse gérée (NON par défaut) @param tretour: 'LISTE' ou 'ANTI' ou 'DIR' """ global chaineretour if casse=="NON": pat=re.compile(pattern,re.IGNORECASE) else: pat=re.compile(pattern) lf=[] rp=[] for i in os.listdir(rep): if not os.path.isdir(rep+'\\'+i): lf.append(i) else: rp.append(i) lst=[] anti=[] for f in lf: if pat.search(f): lst.append(f) else: anti.append(f) if tretour=="ANTI": chaineretour=string.join(anti,'\t') return anti elif tretour=="DIR": chaineretour=string.join(rp,'\t') return rp else: chaineretour=string.join(lst,'\t') return lst def aldirfast(path, recursif=False): """Michel Claveau Informatique Trouve trés vite contenu et taille d'un dossier Ignore ('saute') . et .. Retourne : taille totale nb fichier nb sous-dossiers liste_fichiers liste_path_des_fichiers liste_sous-dossiers liste_path_des_sous-dossiers """ import win32file try: items = win32file.FindFilesW(path + "\\*") except win32file.error, details: self.errors[path] = str(details[-1]) return fichiers=[] fpath=[] srep=[] srpath=[] fdatime=[] fsize=[] totalsize = 0 nbfichiers = 0 nbsousrep = 0 for item in items: #print item #attr = item[0] #datetime = item[1] size = item[-5] name = item[-2] if item[0] & 16: if name != "." and name != "..": srep.append(name) srpath.append(path) nbsousrep += 1 if recursif: tempsize,tempnbfichiers,tempnbsousrep,tempfichiers,tempfpath,tempsrep,tempsrpath = aldirfast(path+'\\'+name,recursif) totalsize += tempsize nbfichiers += tempnbfichiers nbsousrep += tempnbsousrep fichiers.extend(tempfichiers) fpath.extend(tempfpath) srep.extend(tempsrep) srpath.extend(tempsrpath) else: fichiers.append(name) fpath.append(path) fdatime.append(item[1]) fsize.append(item[5]) totalsize += size nbfichiers += 1 return totalsize,nbfichiers,nbsousrep,fichiers,fpath,srep,srpath def aldirultrafast(ppath=None,separ=None): """Michel Claveau Informatique Trouve trés très vite la liste des fichiers d'un dossier simple (pas de récursion ; le dossier ne doit pas se terminer par \) si separ est donné, retourne une chaîne, sinon, une liste. Retourne : liste_fichiers sous forme de liste ou de chaîne séparée par la chapîne separ (paramètre) """ import win32file if ppath=="" or (ppath is None): path=GlobalPARAM[0] separ=GlobalPARAM[1] else: path=ppath try: items=win32file.FindFilesW(path + "\\*") lret=[item[-2] for item in items] if (separ is None) or separ=="": return lret else: return separ.join(lret) except win32file.error, details: #self.errors[path] = str(details[-1]) msginfo("Erreur",str(details[-1])) return def findfinfiles(rep="D:\\dev\\python", pattern="*.py", pcherche="ponx"): #print 10,rep[:2],rep[2:],pattern try: cherche=pcherche.encode('cp1252','ignore') except: cherche=pcherche bufdir=os.getcwd() os.chdir(rep) lfic=rechfilesp(rep[:2], rep[2:], pattern, sousrep=False) lretour=[] for fdetail in lfic: f=fdetail[2]+fdetail[3] try: data=open(f,"rb").read() except: try: f=f.decode('utf-8','ignore') data=open(f,"rb").read() except: pass if data.find(cherche)>-1: #print f ligs=open(f,"rb").readlines() n=0 for l in ligs: n+=1 if l.find(cherche)>-1: #print string.rjust(str(n),5),'\t',l[:-2] chaine=f+'|'+str(n)+'|'+l[:-2] lretour.append(chaine) os.chdir(bufdir) return lretour #*** NEW 21.6.05 v2.31 MODIF:27.6.05 *** def lsousrep(srep,lsou=[],recursif=True): """retourne la liste des sous-repertoires d'un répertoire exemples : lst=lsousrep('D:\\DEV\\Python') lst=lsousrep(r'\\Server\sav\trsfr') #on doit avoir le droit d'accès... join(lsousrep('D:\\DEV\\Python')) # et résultat dans chaineretour """ global chaineretour for i in os.listdir(srep): ste=srep+'\\'+i if os.path.isdir(ste): lsou.append(ste) if recursif: lsou=lsousrep(ste,lsou) chaineretour=SEPARLIGSERIAL.join(lsou) return lsou def lsousreplist(srep,lsou=[],recursif=True): """retourne la liste des sous-repertoires d'un répertoire exemples : lst=lsousrep('D:\\DEV\\Python') lst=lsousrep(r'\\Server\sav\trsfr') #on doit avoir le droit d'accès... join(lsousrep('D:\\DEV\\Python')) # et résultat dans chaineretour """ global chaineretour for i in os.listdir(srep): ste=srep+'\\'+i if os.path.isdir(ste): lsou.append(ste) if recursif: lsou=lsousrep(ste,lsou) return lsou #*** NEW 04.11.2011 *** def lsousrepchaine(srep,lsou=[],recursif=True): """retourne la liste des sous-repertoires d'un répertoire exemples : lst=lsousrep('D:\\DEV\\Python') lst=lsousrep(r'\\Server\sav\trsfr') #on doit avoir le droit d'accès... join(lsousrep('D:\\DEV\\Python')) # et résultat dans chaineretour """ global chaineretour for i in os.listdir(srep): ste=srep+'\\'+i if os.path.isdir(ste): lsou.append(ste) if recursif: lsou=lsousrep(ste,lsou) chaineretour='\t'.join(lsou) return chaineretour #*** NEW 21.6.05 v2.32 MODIF:27.6.05 *** def lsousrepw(srep): """comme lsousrep ; mais réalisé en wrappant le DIR de windows, ce qui est très rapide. ATTENTION : français seulement. """ global chaineretour import subprocess pipe = subprocess.Popen('dir '+srep+' /s /w', shell=True, stdout=subprocess.PIPE).stdout compilre=re.compile(r' Répertoire de ') result=[] for lig in pipe.readlines(): if compilre.search(lig): result.append(lig[15:-2]) chaineretour=SEPARLIGSERIAL.join(result) return result #*** modif 9.3.6 v3.13 *** def lsousrepp(srep): """Spécial PARADOX, en remplacement de lsousrepw comme lsousrep ; mais réalisé en wrappant le DIR de windows, ce qui est très rapide. ATTENTION : français seulement. """ global chaineretour """ pipe = os.popen('dir '+srep+' /s /w') compilre=re.compile(r' Répertoire de ') result=[] for lig in pipe.readlines(): if compilre.search(lig): result.append(lig[15:-2]) chaineretour=SEPARLIGSERIAL.join(result) """ pipe = os.popen('dir '+srep+' /B /S /AD') result=[] for lig in pipe.readlines(): result.append(lig.rstrip('\r\n')) chaineretour=SEPARLIGSERIAL.join(result) #msginfo(srep,str(chaineretour)) return result #***new: 3.215 ; 18.07.2006 *** def commandsousrep(srep, repattern, commande='', visu='NON', casse='NON'): """ parcours tous les sous-répertoire d'un directory pour chaque répertoire, sélectionne les nfichiers selon une expression régulière (repattern) pour chacun des fichiers sélectionnés, lance une commande, dans laquelle des remplacement sont effectués : %(fichier)s nom du fichier @Exemples: commandsousrep('D:\\Dev',".zip","pkzip -d %(fichier)s *.zip") commandsousrep('T:\\',".zip","@echo Zip dans %(directory)s: %(fichier)s") """ bufrep=os.getcwd() os.chdir(srep) ldir=lsousrepp(srep) for directory in ldir: os.chdir(directory) listzip=aldirre(directory,repattern) if len(listzip)>0: if visu=="OUI": print directory,listzip for fichier in listzip: os.system(commande%locals()) if visu=="OUI": print'-'*55 os.chdir(bufrep) #***new: 3.215 ; 18.07.2006 *** def commandsousrepwalk(srep, repattern, commande, visu='NON', casse='NON'): """ parcours tous les sous-répertoire d'un directory pour chaque répertoire, sélectionne les nfichiers selon une expression régulière (repattern) pour chacun des fichiers sélectionnés, lance une commande, dans laquelle des remplacement sont effectués : %(fichier)s nom du fichier @Exemples: commandsousrep('D:\\Dev',".zip","pkzip -d %(fichier)s *.zip") commandsousrep('T:\\',".zip","@echo Zip dans %(directory)s: %(fichier)s") """ def trtfichiers(arg,directory,fichiers): if arg[1]=="OUI": print directory for fichier in fichiers: if arg[0].search(fichier): if os.getcwd!=directory: os.chdir(directory) os.system(commande%locals()) if visu=="OUI": print'-'*55 bufrep=os.getcwd() os.chdir(srep) if casse=="NON": pat=re.compile(repattern,re.IGNORECASE) else: pat=re.compile(repattern) os.path.walk(srep, trtfichiers, [pat,commande,visu]) os.chdir(bufrep) #*** NEW 21.6.05 v2.32 modif 28.6.05 v2.32a *** def rechfilesw(driv, srep, fichiers): """recherche de fichiers, par wrapping de DIR """ global chaineretour import subprocess if not srep.endswith('\\'): srep+='\\' ordre='dir "'+driv+srep+fichiers+'" /b /s' chaineretour=ordre pip = subprocess.Popen(ordre, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, bufsize=1).stdout stmp=pip.readlines() result=[] nb=0 for lig in stmp: nb+=1 rpath,rfile=os.path.split(lig) result.append([driv,rpath[len(driv):],rfile[:-2],rpath[len(driv)+len(srep):]]) chaineretour='' for l in result: chaineretour+=SEPARITEMSERIAL.join(l)+SEPARLIGSERIAL return result #*** NEW 28.6.05 v2.32b *** def rechfilesp(driv, srep, fichiers, sousrep=False): """recherche de fichiers, par wrapping de DIR """ global chaineretour if not srep.endswith('\\'): srep+='\\' if sousrep: ordre='dir "'+driv+srep+'"'+fichiers+' /s /b' else: ordre='dir "'+driv+srep+'"'+fichiers+' /b' pip = os.popen(ordre) stmp=pip.readlines() result=[] nb=0 for lig in stmp: nb+=1 rpath,rfile=os.path.split(lig) rfile,rext=os.path.splitext(lig) #print 1671,rfile result.append([driv,rpath[len(driv):],rfile,rext[:-1]]) chaineretour='' for litem in result: try: l=[item.encode('cp1252','replace') for item in litem] chaineretour+=SEPARITEMSERIAL.join(l)+SEPARLIGSERIAL except: l=litem #chaineretour+=SEPARITEMSERIAL.join(l)+SEPARLIGSERIAL return result #*** NEW 28.6.05 v2.32b *** def rechfiles98(driv, srep, fichiers): """recherche de fichiers, par wrapping de DIR """ global chaineretour if not srep.endswith('\\'): srep+='\\' ordre='dir "'+driv+srep+'"'+fichiers+' /s /b' pip = os.popen(ordre) stmp=pip.readlines() result=[] nb=0 for lig in stmp: nb+=1 rpath,rfile=os.path.split(lig) result.append([driv,rpath[len(driv):],rfile[:-2],rpath[len(driv)+len(srep):]]) chaineretour='' for l in result: chaineretour+=SEPARITEMSERIAL.join(l)+SEPARLIGSERIAL return result #*** NEW v3.308 *** def processdict(): """ Cherche la liste des process en cours ; retourne deux dictionnaires: 1) key = nom_process ; data = pid 2) key = pid ; data = nom_process """ a = os.popen4('tasklist /NH') a[0].flush() time.sleep(0.0) lret=a[1].readlines() dp={} pid={} for i in lret: l=i.split() #print len(l),l if len(l)>0: if l[0]=="System" and l[1]=="Idle": continue dp[l[0]]=l[1] pid[l[1]]=l[0] return dp,pid # ver 3.264 def choiceopenfile(_InitialDir='C:\\', _File='', _Title='Choix du fichier à ouvrir', _Filter='Tous les Fichiers\0*.*\0',_CustomFilter='',_FilterIndex=0): """ dir initial fichier_proposé extension_par_defaut titre filtre exemple : choiceopenfile('C:\\Dev\\bat\\','toto.txt', 'txt', 'Choix du fichier à ouvrir', 'Python scripts\0*.py;*.pyw;*.pys\0Fichiers css\0*.css\0') """ import win32gui, win32con, os _DefExt='' # extension par défaut ? """ win32con.OFN_FILEMUSTEXIST win32con.OFN_ALLOWMULTISELECT win32con.OFN_EXPLORER OFN_DONTADDTORECENT = &H2000000 OFN_ENABLEHOOK = &H20 OFN_ENABLEINCLUDENOTIFY = &H400000 OFN_ENABLESIZING = &H800000 OFN_ENABLETEMPLATE = &H40 OFN_ENABLETEMPLATEHANDLE = &H80 OFN_EX_NOPLACESBAR = &H1 OFN_FORCESHOWHIDDEN = &H10000000 OFN_HIDEREADONLY = &H4 OFN_SHAREFALLTHROUGH = 2 OFN_SHARENOWARN = 1 OFN_USEMONIKERS = &H1000000 OFN_ALLOWMULTISELECT &H200 Autoriser la sélection multiple de fichiers. OFN_CREATEPROMPT &H2000 Afficher une fenêtre de confirmation de création de fichier. OFN_EXPLORER &H80000 Donne un style 'Explorer' à la boîte de dialogue (par défaut). OFN_EXTENSIONDIFFERENT &H400 Indique que l'utilisateur a choisi une extension différente de celle par défaut. OFN_FILEMUSTEXIST &H1000 Seuls des fichiers existants peuvent être saisis. OFN_HIDEREADONLY &H4 Case à cocher 'Lecture seule' invisible. OFN_LONGNAMES &H200000 Gestion des noms longs pour les boîtes de dialogue n'ayant pas le style 'Explorer'. OFN_NOCHANGEDIR &H8 Conserve le répertoire d'origine à la fermeture de la fenêtre. OFN_NODEREFERENCELINKS &H100000 La boîte de dialogue prendra le nom et le chemin du raccourci sélectionné. OFN_NOLONGNAMES &H40000 Utilise les noms courts de fichier (sans effet dans le cas des fenêtres du type 'Explorer'). OFN_NONETWORKBUTTON &H20000 Cache (désactive) le bouton 'Réseau'. OFN_NOREADONLYRETURN &H8000 Ne sélectionne pas la case à cocher 'Lecture seule'. OFN_NOTESTFILECREATE &H10000 Le fichier ne sera pas créé avant la fermeture de la fenêtre. OFN_NOVALIDATE &H100 Ne vérifie pas la validité de la saisie (validité du nom de fichier). OFN_OVERWRITEPROMPT &H2 Afficher un message de confirmation d'écrasement de fichier si celui-ci existe déjà. OFN_PATHMUSTEXIST &H800 Les chemins et fichiers saisis doivent exister. OFN_READONLY &H1 La case 'Lecture seule' est cochée à la création de la fenêtre. OFN_SHAREAWARE &H4000 Ignorer les erreurs de partage réseau. OFN_SHOWHELP &H10 Afficher le bouton 'Aide' dans la boîte de dialogue. """ _Flags=win32con.OFN_ALLOWMULTISELECT|win32con.OFN_EXPLORER _Flags=win32con.OFN_EXPLORER try: fname=win32gui.GetOpenFileNameW(InitialDir=_InitialDir, Flags=_Flags, File=_File, DefExt=_DefExt, Title=_Title, Filter=_Filter, CustomFilter=_CustomFilter, FilterIndex=_FilterIndex)[0] except: fname=None #fname=win32gui.GetOpenFileNameW(InitialDir="C:\\dev")[0] return fname def isnumlock(turn_on) : """ Teste le clavier : si verrouillage-numérique (NumLock) est actif """ return windll.user32.GetKeyState( VK_NUMLOCK ) & 1 def iscapslock(): """ Teste le clavier : si verrouillage-majuscules (CapsLock) est actif """ return ctypes.windll.user32.GetKeyState( win32con.VK_CAPITAL ) & 1 def capture(): """ Capture des touches du clavier, durant un maximum de 120 sec {Maj}{Echap} pour terminer l'enregistrement. utilisé par capturemacro() """ lkey=[7,8,9,10,13] lkey.extend(range(19,255)) #print lkey bufp=0 deb=time.time() clavt=[] clavc=[] while time.time()-deb<120: win32gui.PumpWaitingMessages() time.sleep(0.03) for k in lkey: if win32api.GetAsyncKeyState(win32con.VK_ESCAPE) & 0x8000: if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: return clavt,clavc if k in (0,129,160,161,162,163,164,165,186,255): continue if win32api.GetAsyncKeyState(k) & 0x8000: #print 42,bufp,k if bufp==k: nb_return=0 while win32api.GetAsyncKeyState(k) & 0x8000: nb_return+=1 if nb_return>19: break win32gui.PumpWaitingMessages() time.sleep(0.01) bufp=0 continue bufp=k keycompl="" #if windll.user32.GetKeyState( VK_CAPITAL ) & 1: if iscapslock(): keycompl += "CapsLock+" if win32api.GetAsyncKeyState(win32con.VK_CONTROL) & 0x8000: keycompl += "Ctrl+" if win32api.GetAsyncKeyState(win32con.VK_SHIFT) & 0x8000: keycompl += "Shift+" if win32api.GetAsyncKeyState(win32con.VK_MENU) & 0x8000: keycompl += "Alt+" if k in (0,129,160,161,162,163,164,165,186,255): pass #print 110,k else: #print 2526,k,keycompl clavt.append(k) clavc.append(keycompl) def capturemacro(fichier=None): """ Capture un ensemble de touches du clavier, et prépare les données ( on termine par {Maj}{Echapp} ) si fichier is not None, les données sont "cPicklisées" """ ct,cc=capture() for i in range(len(ct)): t=ct[i] c=cc[i] if t>48 and t<90: ct[i]=chr(t).lower() else: pass if fichier is not None: f=open(fichier,'wb') cPickle.dump([ct,cc],f,cPickle.HIGHEST_PROTOCOL) f.close() def clavier(chaine, shift=False,control=False,alt=False, delaik=0): """ émule le clavier (envoie des touches du clavier) Exemple : clavier(win32con.VK_RETURN) clavier(u"AZERTYUIOP") clavier(win32con.VK_RETURN) clavier("V",control=True) time.sleep(1) clavier(win32con.VK_F4, alt=True) time.sleep(0.250) clavier(win32con.VK_RIGHT) time.sleep(0.250) clavier(win32con.VK_RETURN) time.sleep(0.250) """ ctypes.windll.user32.VkKeyScanW.restype = ctypes.c_short ctypes.windll.user32.VkKeyScanW.argtypes = [ctypes.c_wchar] DWORD = ctypes.c_ulong LONG = ctypes.c_long WORD = ctypes.c_ushort def LoByte(val): "Return the low byte of the value" return val & 0xff def HiByte(val): "Return the high byte of the value" return (val & 0xff00) >> 8 class MOUSEINPUT(ctypes.Structure): "Needed for complete definition of INPUT structure - not used" _pack_ = 2 _fields_ = [ ('dx', LONG), ('dy', LONG), ('mouseData', DWORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', DWORD), ] assert ctypes.sizeof(MOUSEINPUT) == 24, ctypes.sizeof(MOUSEINPUT) assert ctypes.alignment(MOUSEINPUT) == 2, ctypes.alignment(MOUSEINPUT) class KEYBDINPUT(ctypes.Structure): "A particular keyboard event" _pack_ = 2 _fields_ = [ ('wVk', WORD), ('wScan', WORD), ('dwFlags', DWORD), ('time', DWORD), ('dwExtraInfo', DWORD), ] assert ctypes.sizeof(KEYBDINPUT) == 16, ctypes.sizeof(KEYBDINPUT) assert ctypes.alignment(KEYBDINPUT) == 2, ctypes.alignment(KEYBDINPUT) class HARDWAREINPUT(ctypes.Structure): "Needed for complete definition of INPUT structure - not used" _pack_ = 2 _fields_ = [ ('uMsg', DWORD), ('wParamL', WORD), ('wParamH', WORD), ] assert ctypes.sizeof(HARDWAREINPUT) == 8, ctypes.sizeof(HARDWAREINPUT) assert ctypes.alignment(HARDWAREINPUT) == 2, ctypes.alignment(HARDWAREINPUT) class UNION_INPUT_STRUCTS(ctypes.Union): "The C Union type representing a single Event of any type" _fields_ = [ ('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT), ] assert ctypes.sizeof(UNION_INPUT_STRUCTS) == 24, ctypes.sizeof(UNION_INPUT_STRUCTS) assert ctypes.alignment(UNION_INPUT_STRUCTS) == 2, ctypes.alignment(UNION_INPUT_STRUCTS) class INPUT(ctypes.Structure): "See: http://msdn.microsoft.com/en-us/library/ms646270%28VS.85%29.aspx" _pack_ = 2 _fields_ = [ ('type', DWORD), ('_', UNION_INPUT_STRUCTS), ] assert ctypes.sizeof(INPUT) == 28, ctypes.sizeof(INPUT) assert ctypes.alignment(INPUT) == 2, ctypes.alignment(INPUT) INPUT_KEYBOARD = 1 KEYEVENTF_EXTENDEDKEY = 1 KEYEVENTF_KEYUP = 2 KEYEVENTF_UNICODE = 4 KEYEVENTF_SCANCODE = 8 VK_SHIFT = 16 VK_CONTROL = 17 VK_MENU = 18 #def k2(touche, **kw): def k2(touche, shift=False,control=False,alt=False, delaik=0): """ print 1002,kw if 'shift' in kw: shift=kw['shift'] if 'control' in kw: control=kw['control'] if 'alt' in kw: alt=kw['alt'] if 'delaik' in kw: delaik=kw['delaik'] """ if shift: # appui sur shift inputs = (INPUT * 1)() key=win32con.VK_SHIFT if ( (key >= 33 and key <= 46) or (key >= 91 and key <= 93) ): flags = KEYEVENTF_EXTENDEDKEY; else: flags = 0 vk_shift,scan_shift = key, ctypes.windll.user32.MapVirtualKeyW(key, 0) inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_shift inputs[0]._.ki.wScan = scan_shift inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if control: # appui sur control inputs = (INPUT * 1)() key=win32con.VK_CONTROL if ( (key >= 33 and key <= 46) or (key >= 91 and key <= 93) ): flags = KEYEVENTF_EXTENDEDKEY; else: flags = 0 vk_control,scan_control = key, ctypes.windll.user32.MapVirtualKeyW(key, 0) inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_control inputs[0]._.ki.wScan = scan_control inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if alt: # appui sur alt inputs = (INPUT * 1)() key=win32con.VK_MENU if ( (key >= 33 and key <= 46) or (key >= 91 and key <= 93) ): flags = KEYEVENTF_EXTENDEDKEY; else: flags = 0 vk_alt,scan_alt = key, ctypes.windll.user32.MapVirtualKeyW(key, 0) inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_alt inputs[0]._.ki.wScan = scan_alt inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) # appui sur la touche if isinstance(touche,int): vk,scan = touche, ctypes.windll.user32.MapVirtualKeyW(touche, 0) elif shift or control or alt: vkey_scan = LoByte(ctypes.windll.user32.VkKeyScanW(touche)) vk,scan = vkey_scan, ctypes.windll.user32.MapVirtualKeyW(vkey_scan, 0) else: vk=0 scan=ord(touche) inputs = (INPUT * 2)() flags = KEYEVENTF_UNICODE inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk inputs[0]._.ki.wScan = scan inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE inputs[1].type = INPUT_KEYBOARD inputs[1]._.ki.wVk = vk inputs[1]._.ki.wScan = scan inputs[1]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if delaik>0: time.sleep(delaik) if alt: # relâche control inputs = (INPUT * 1)() inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_alt inputs[0]._.ki.wScan = scan_alt inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if control: # relâche control inputs = (INPUT * 1)() inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_control inputs[0]._.ki.wScan = scan_control inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if shift: # relâche shift inputs = (INPUT * 1)() inputs[0].type = INPUT_KEYBOARD inputs[0]._.ki.wVk = vk_shift inputs[0]._.ki.wScan = scan_shift inputs[0]._.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP ctypes.windll.user32.SendInput(len(inputs), ctypes.byref(inputs), ctypes.sizeof(INPUT)) if isinstance(chaine,int): k2(chaine, shift, control, alt, delaik) else: for c in chaine: k2(c, shift, control, alt, delaik) def playmacro(fichier, delaik=0, mode='JOUER'): """ Joue une macro-clavier enregistrée par capturemacro() c'est une émulation du clavier delaik est le délai entre chaque touche (0 = pas de délai) mode='LISTER' permet de voir (print) le contenu de la macro, au lieu de la jouer """ f=open(fichier,'rb') ct,cc = cPickle.load(f) f.close() ttrans={ '1': u'&', "Shift+1": u"1", '2': u'é', "Shift+2": u"2", '3': u'"', "Shift+3": u"3", '4': u"'", "Shift+4": u"4", '5': u'(', "Shift+5": u"5", '6': u'-', "Shift+6": u"6", '7': u'è', "Shift+7": u"7", '8': u'_', "Shift+8": u"8", '9': u'ç', "Shift+9": u"9", '0': u'à', "Shift+à": u"0", '°': u')', "Shift+°": u"°", '+': u'=', "Shift++": u"+", chr(192): u"ù", "Shift+"+chr(192): u"%", chr(220): u"*", "Shift+"+chr(220): u"µ", chr(188): u",", "Shift+"+chr(188): u"?", chr(190): u";", "Shift+"+chr(190): u".", chr(191): u":", "Shift+"+chr(191): u"/", chr(223): u"!", "Shift+"+chr(223): u"§", chr(226): u"<", "Shift+"+chr(226): u">", } ctrans={ '1': "", "Shift+1": "", '2': "", "Shift+2": "", '3': "", "Shift+3": "", '4': "", "Shift+4": "", '5': "", "Shift+5": "", '6': "", "Shift+6": "", '7': "", "Shift+7": "", '8': "", "Shift+8": "", '9': "", "Shift+9": "", '0': "", "Shift+0": "", '°': "", "Shift+°": "", '+': "", "Shift++": "", chr(192): u"", "Shift+"+chr(192): u"", chr(220): u"", "Shift+"+chr(220): u"", chr(188): u"", "Shift+"+chr(188): u"", chr(190): u"", "Shift+"+chr(190): u"", chr(191): u"", "Shift+"+chr(191): u"", chr(223): u"", "Shift+"+chr(223): u"", chr(226): u"", "Shift+"+chr(226): u"", } for t,c in zip(ct,cc): if t==20: continue shift=False control=False alt=False flag_capslock=False if "Shift" in c: shift=True if "Ctrl" in c: control=True if "Alt" in c: alt=True if "CapsLock+" in c: flag_capslock=True if flag_capslock: shift = not shift clef="" if shift: clef+="Shift+" if control: clef+="Ctrl+" if alt: clef+="Alt+" clef+=str(t) if not isinstance(t,int): if clef in ttrans: t=ttrans[clef] c=ctrans[clef] if mode=='LISTER': print "Touche:",t, " shift:",shift," control:",control," alt:",alt else: clavier(t, shift,control,alt, delaik) #*** NEW *** def callbacksurv(f, *par): global chaineretour st=f+"(" for i in par: st=st+"r'"+str(i)+"'," st=st[:-1]+")" fcod=compile(st,'ponx:callback.'+f,'exec') exec(fcod,globals(),globals()) #*** NEW *** def survfile(fichier, delai=5,duree=60, dest=None, trt=None): """ Attend, durant 'duree' secondes, que le fichier 'fichier' existe, et en étant agé de moins de 'delai' secondes. Si le fichier est trouvé, le traitement 'trt' est effectué. Exemples: survfile(r'c:\t\fax.pdf', dest=r'c:\fax\f1234.pdf') #copie, par défaut survfile(r'c:\t\fax.pdf', dest=r'c:\t\f1234.pdf',trt='rename') survfile(r'c:\t\fax.pdf', dest='c:\\fax\\',trt='move') survfile(r'c:\t\fax.pdf', dest=r'c:\fax\f1234.pdf',trt='move') survfile(r'c:\t\fax.pdf', trt='del') @param fichier: nom (long, avec path) du fichier à surveiller. @param delai: âge (en secondes) maximum du fichier ; 5 par défaut @param duree: durée (en secondes) de la surveillance ; 60 secondes par défaut @param dest: fichier (nom long) de destination ; facultatif ; selon le traitement. @param trt: Traitement à effectuer 'COPIE' par défaut. Peut être : - 'copie' copie le fichier sur destination - 'copy' idem - 'del' supprime le fichier - 'move' déplace le fichier ; écrase ni nécessaire - 'rename' renomme le fichier ; la destination (nouveau nom) ne doit pas exister (pas d'écrasement). - 'callback:XXX' une fonction callback 'XXX', que vous pouvez définir. Elle sera appelée avec les deux paramètres 'fichier' et 'dest' """ import shutil,os,os.path,time def filetraite(fichier, dest=None, trt='copie'): global chaineretour if trt is None: trt='COPIE' try: if trt.upper()=='COPIE' or trt.upper()=='COPY': #écrase si nécessaire if not(dest is None): shutil.copy2(fichier,dest) chaineretour="OK" elif trt.upper()=='DEL': os.remove(fichier) chaineretour="OK" elif trt.upper()=='MOVE': #écrase si nécessaire if not(dest is None): shutil.move(fichier,dest) chaineretour="OK" elif trt.upper()=='RENAME': #la destination ne doit pas exister (pas d'écrasement) if not(dest is None): os.rename(fichier,dest) chaineretour="OK" elif trt.upper()[:9]=='CALLBACK:': try: callbacksurv(trt[9:], fichier, dest) chaineretour="OK" except: pass chaineretour=_("Erreur") except: chaineretour=_('Erreur de ')+trt+', '+_('avec')+' '+fichier+_(' et ')+dest return chaineretour debut=time.time() maintenant=debut while maintenant-debut1024: try: TCPclose() except: chaineretour='Error close (TCPersistenvoitxt).' return chaineretour if TCPconnect()!='OK.': return chaineretour try: TCPconnexion.settimeout(0.02) except: chaineretour='Error settimeout (TCPersistenvoitxt).' #TCPclose() return chaineretour #*** v3.249 *** def TCPersistenvoippaw(id, txt='', tpstyp='', secur='' ): """Envoi une chaîne-fichier (nom=id) au serveur de télépersistence, avec id = identifiant, sert aussi de nom de fichier txt = chaîne """ global TCPconnexion,chaineretour,GlobalPARAM if TCPconnexion is None : TCPconnect() else: #print "va envoyer" if txt=='': txt=GlobalPARAM[0] param1=id+" "*20 # Nom 20 caractères param1=param1[:20] param2=str(len(txt))+" "*10 # longueur (10 caractères) param2=param2[:10] param3=str(tpstyp)+" "*10 # type (10 caractères) param3=param3[:10] param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] TCPconnexion.settimeout(3) tete='PPA\t'+param1+param2+param3+param4 bloc=tete+txt try: TCPconnexion.sendall(bloc) chaineretour='OK.ppa.'+str(len(bloc)) except: if TCPconnect()=='OK.' : try: TCPconnexion.sendall(bloc) chaineretour='OK2.ppa.'+str(len(bloc)) except: chaineretour='Error.ppa.'+str(len(bloc)) else: chaineretour='Pas de connexion.ppa.'+str(len(bloc)) return chaineretour def TCPersistenvoifin(secur=None): global TCPconnexion,chaineretour TCPconnexion.settimeout(0.24) if TCPconnexion is None : chaineretour='FIN non parti (connexion fermée).' return try: param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] st='FIN '+" "*40+param4 TCPconnexion.sendall(st[:54]) TCPclose() except: pass def TCPersistgettxt(id, tpstyp='', secur='', delai=0.0240): #0.024 global TCPconnexion,chaineretour if TCPconnexion is None : TCPconnect() try: if TCPconnexion is None : chaineretour='No connect.' return except: chaineretour='Pb TCPconnexion' return param1=id+" "*10 # Nom 20 caractères param1=param1[:10] param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] st='GET '+param1+" "*30+param4 if delai<0.01: TCPconnexion.settimeout(None) else: TCPconnexion.settimeout(delai) #TCPconnexion.setblocking(0) try: TCPconnexion.sendall(st[:54]) #TCPconnexion.send(st[:54]) except: chaineretour='GET.Error as send command.' return chaineretour #time.sleep(delai) buffer='' data='' taillebloc=1024 #4096 while 1 : #time.sleep(0.01) try: data = TCPconnexion.recv(taillebloc) if not data: break buffer=buffer+data while len(data)==taillebloc: data = TCPconnexion.recv(taillebloc) if not data: break buffer=buffer+data if not data: break except: #data = None break if not data: break #print 2838,len(buffer) #print "2263, len.buffer",len(buffer) if delai<0.01: TCPconnexion.settimeout(None) else: TCPconnexion.settimeout(0.024) chaineretour=buffer time.sleep(0.01) return chaineretour def TCPersistenvoifichier(id, nomfichier, tpstyp='', secur=''): global TCPconnexion,chaineretour list = string.split(nomfichier,'\\') nomlocal=list[-1]+" "*50 data=open(nomfichier, "rb").read() TCPersistenvoitxt(id, nomlocal[:50]+data, tpstyp, secur) chaineretour="fichier:"+list[-1]+' '+str(len(data)) return chaineretour def TCPersistgetfichier(id, nomfichier='', tpstyp='', secur=''): global TCPconnexion,chaineretour data=TCPersistgettxt(id,'',secur) if nomfichier=='': nomfichier=data[:50].strip() open(nomfichier,'wb').write(data[50:]) #*** 3.247 def TCPersistenvoifichierppaw(id, nomfichier, tpstyp='', secur=''): global TCPconnexion,chaineretour list = string.split(nomfichier,'\\') nomlocal=list[-1]+" "*50 data=open(nomfichier, "rb").read() TCPersistenvoippaw(id, data, tpstyp, secur) chaineretour="fichier.PPAW:"+list[-1]+' '+str(len(data)) return chaineretour def TCPersistdeltxt(id): global TCPconnexion,chaineretour """ if TCPconnect()<>'OK.' : chaineretour='No connect.' """ st='DEL '+id+" "*54 TCPconnexion.send(st[:54]) buffer='' def TCPersistlit(id): global TCPconnexion,chaineretour """ if TCPconnect()<>'OK.' : chaineretour='No connect.' """ st='LIT '+id+" "*54 TCPconnexion.send(st[:54]) buffer='' def TCPersistsav(id): global TCPconnexion,chaineretour """ if TCPconnect()<>'OK.' : chaineretour='No connect.' """ st='SAV '+id+" "*54 TCPconnexion.send(st[:54]) buffer='' def TCPersistgetelt(id='', secur='', delai=0.15): global TCPconnexion,chaineretour if TCPconnexion is None : TCPconnect() else: chaineretour="bof" param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] param1=id+" "*10 # Nom 20 caractères param1=param1[:10] param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] st='ELT '+param1+" "*30+param4 TCPconnexion.settimeout(0.02) #TCPconnexion.setblocking(0) try: TCPconnexion.sendall(st[:54]) except: chaineretour='ELT.Error as send command.' return chaineretour time.sleep(delai) buffer='' while 1 : try: data = TCPconnexion.recv(1024) except: data = None break if not data: break buffer=buffer+data #print "len.buffer",len(buffer) chaineretour=buffer return chaineretour def TCPersistgetlst(secur='', delai=0.15): global TCPconnexion,chaineretour if TCPconnexion is None : TCPconnect() else: chaineretour="bof" param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] st='LST '+" "*40+param4 TCPconnexion.settimeout(0.02) #TCPconnexion.setblocking(0) try: TCPconnexion.sendall(st[:54]) except: chaineretour='GET.Error as send command.' return chaineretour time.sleep(delai) buffer='' while 1 : try: data = TCPconnexion.recv(1024) except: data = None break if not data: break buffer=buffer+data #print "len.buffer",len(buffer) chaineretour=buffer return chaineretour def TCPersistPexec(id, tpstyp='', secur='', delai=5): global TCPconnexion,chaineretour if TCPconnexion is None : TCPconnect() else: param3=str(tpstyp)+" "*10 # securite (10 caractères) param3=param3[:10] param4=str(secur)+" "*10 # securite (10 caractères) param4=param4[:10] st='PEX '+id+" "*34 st=st[:34]+param3+param4 TCPconnexion.settimeout(delai) #TCPconnexion.setblocking(0) TCPconnexion.sendall(st[:54]) buffer='' time.sleep(0.2) while 1 : try: data = TCPconnexion.recv(1024) except: data = None break if not data: break buffer=buffer+data TCPconnexion.settimeout(0.02) chaineretour=buffer return chaineretour def TCPersistCexec(id, txt='', tpstyp='', secur='', delai=5): global TCPconnexion,chaineretour if TCPconnexion is None : TCPconnect() else: if txt=='': txt=GlobalPARAM[0] def scomplete(text,long): st = text+' '*long return(st[:long]) tnom=scomplete(id,20) tlong=scomplete(str(len(txt)),10) tsecur=scomplete(secur,10) ttype=scomplete(tpstyp,10) bloc="CEX "+tnom+tlong+ttype+tsecur+txt try: TCPconnexion.sendall(bloc) chaineretour='OK.'+str(len(bloc)) except: if TCPconnect()=='OK.' : try: TCPconnexion.sendall(bloc) chaineretour='OK.'+str(len(bloc)) except: chaineretour='Error.'+str(len(bloc)) if len(bloc)>1024: TCPclose() TCPconnect() TCPconnexion.settimeout(delai) #TCPconnexion.setblocking(0) buffer='' time.sleep(0.5) while 1 : try: data = TCPconnexion.recv(1024) except: data = None break if not data: break buffer=buffer+data TCPconnexion.settimeout(0.02) chaineretour=buffer return chaineretour #*** NEW *** def TCPersistgettxtUnit(id, tpstyp='', secur='', TCPHOST=None, TCPPORT=22222): """ lecture directe d'une chaîne depuis TPS """ if TCPHOST is None: TCPHOST=socket.gethostbyname(socket.gethostname()) try: TCPconnexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPconnexion.connect((TCPHOST,TCPPORT)) #print 'Ok',TCPHOST,TCPPORT except: return('Error') TCPconnexion.settimeout(1) def scomplete(text,long): st = text+' '*long return(st[:long]) tnom=scomplete(id,20) tlong=scomplete(' ',10) tsecur=scomplete(secur,10) ttype=scomplete(tpstyp,10) st="GET "+tnom+tlong+ttype+tsecur+' '*54 TCPconnexion.send(st[:54]) buffer='' while 1 : data='' try: data = TCPconnexion.recv(1024) except: pass if not data: break buffer=buffer+data TCPconnexion.close() TCPconnexion=None return buffer #*** NEW *** def TCPersistenvoitxtUnit(id, txt, tpstyp='', secur='', TCPHOST=None, TCPPORT=22222): """ écriture directe d'une chaîne vers TPS """ if TCPHOST is None: TCPHOST=socket.gethostbyname(socket.gethostname()) try: TCPconnexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPconnexion.connect((TCPHOST,TCPPORT)) except: return _('Erreur ouverture socket.') def scomplete(text,long): st = text+' '*long return(st[:long]) tnom=scomplete(id,20) tlong=scomplete(str(len(txt)),10) tsecur=scomplete(secur,10) ttype=scomplete(tpstyp,10) bloc="SET "+tnom+tlong+ttype+tsecur+txt try: TCPconnexion.send(bloc) TCPconnexion.close() TCPconnexion=None return "OK" except: TCPconnexion.close() TCPconnexion=None return 'Erreur' #*** NEW *** def TCPersistdeltxtUnit(id, tpstyp='', secur='', TCPHOST=None, TCPPORT=22222): """ suppression direct d'un chaîne sur TPS """ if TCPHOST is None: TCPHOST=socket.gethostbyname(socket.gethostname()) try: TCPconnexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TCPconnexion.connect((TCPHOST,TCPPORT)) except: return _('Erreur ouverture socket.') st='DEL '+id+" "*54 try: TCPconnexion.send(st[:54]) TCPconnexion.close() TCPconnexion=None return "OK" except: TCPconnexion.close() TCPconnexion=None return _('Erreur') def mailslotserver(duree=999999, systemname='.', mailslotname="waitfor.exe", signal="SIGNAL"): """Attend (surveille) un mailslot Exemple : flag,data=mailslot.mailslotserver( duree=600, systemname=".", mailslotname="waitfor.exe", signal="SIGNAL" ) """ import ctypes, win32file myslot = '\\\\'+systemname+'\\mailslot\\'+mailslotname+'\\'+signal nbs=ctypes.c_long(duree*1000) hReceive = ctypes.windll.kernel32.CreateMailslotA(myslot, 0, nbs, 0) if hReceive == -1: data="Access error to Mailslot" return False,data buffer = win32file.AllocateReadBuffer(400) try: rc, data = win32file.ReadFile(hReceive, buffer) except: data="out of time" return False,data return True,data def mailslotclient( systemname='.', mailslotname="waitfor.exe", signal="SIGNAL", data='ABC'): """Envoie un message par mailslot Exemples : mailslotclient( systemname="*", mailslotname="waitfor.exe", signal="SIGNAL", data="TESTCLIENT et c'est noël €" ) mailslotclient( systemname="ServeurCPQ", mailslotname="waitfor.exe", signal="SYNCHRO", data="Terminé" ) """ import win32file,win32con #print 23,'\\\\'+systemname+'\\mailslot\\'+mailslotname+'\\'+signal mailslot = win32file.CreateFile('\\\\'+systemname+'\\mailslot\\'+mailslotname+'\\'+signal, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None) #print 24,"mailslot",mailslot import time time.sleep(0.1) win32file.WriteFile(mailslot, data) mailslot.Close() #*** NEW v2.34 *** def metmmap10(st,cod='TMPCODE', maxi=32767): import mmap GlobalMMAP[cod]=mmap.mmap(0,maxi,cod) tete=str(len(st))+" "*10 GlobalMMAP[cod].seek(0) GlobalMMAP[cod].write(tete[:10]+st) GlobalMMAP[cod].flush() #GlobalMMAP[cod].close() # ne pas 'décommenter' #*** MODIF v3.07 (pour chaîne vide) *** def litmmap10(cod='TMPCODE', maxi=32767): import mmap xm=mmap.mmap(0,maxi,cod) xm.seek(0) long=0 try: long=int(xm.read(10).rstrip()) return(xm.read(long)) except: return('') #return(xm.read(int(xm.read(10).rstrip()))) #*** NEW v2.34 *** def parmmap(cod='TMPCODE'): metmmap10(GlobalPARAM[0]) #*** NEW v2.34 *** def startfilemmap(cod='TMPCODE', maxi=32767, fichier='Temp.pyw'): xm=litmmap10(cod,maxi) f.open(ponxdir()+'\\'+fichier,'wb').write(xm) os.startfile(ponxdir()+'\\'+fichier) #*** NEW v2.34 *** def startfileparam(fichier='Temp.pyw'): f=open(ponxdir()+'\\'+fichier,'wb').write(GlobalPARAM[0]) os.startfile(ponxdir()+'\\'+fichier) class voix(object): """ Cette classe permet de faire de la synthèse vocale, via Sapi.Spvoice # voir http://msdn.microsoft.com/en-us/library/ms723627(VS.85).aspx exemple: v=voix() v.rate(2) v.volume(80) v.setvoix(0) v.speak("Ceci est un test.",0) del(v) """ def __init__(self): self.voix=win32com.client.Dispatch('Sapi.SpVoice') def getinformation(self): """ donne quelques informations sur les voix disponibles. """ lr=[] for v in self.voix.GetVoices(): dr={} dr['description']=v.GetDescription() dr['gender']=v.GetAttribute("Gender") dr['name']=v.GetAttribute("Name") dr['vendor']=v.GetAttribute("Vendor") dr['rate']=self.voix.Rate dr['volume']=self.voix.Volume lr.append(dr) return lr def setvoix(self, numnom=0): """ Met (choisi) une voix, par son numéro (0 à n) """ n=0 for v in self.voix.GetVoices(): if n==numnom: self.voix.Voice = v break n+=1 def rate(self,valeur=0): """ Met la vitesse (de -10 à +10) """ self.voix.Rate=valeur def volume(self,valeur=90): """ Met le volume (de 0 à 100) """ self.voix.Volume=valeur def speak(self,texte="",flag=0): """ Parle (lance la synthèce vocale), avec : flag 0 attend la fin du parlé flag 1 n'attend pas flag 2 purge l'encours avant de parler flag 4 le texte est un nom de fichier (pas testé) """ self.voix.Speak(texte,flag) def gspeak(self,flag=0): self.speak(u1252(GlobalPARAM[0]),flag) def wait(self): """ Si speak a été lancé sans attente, attend la fin du parlé. """ self.voix.WaitUntilDone(-1) def pause(self): """ Si speak a été lancé sans attente, met le parlé en pause. """ self.voix.Pause() def resume(self): """ Si le parlé était en pause, le fait continuer (reprendre) """ self.voix.Resume() def vocalrecord(commande, nomfichier="C:\\MESSAGE.WAV"): global chaineretour,messagevocal if commande=="RECORD": import recordmci messagevocal=recordmci.mci() messagevocal.record() if commande=="RECSTOP": messagevocal.finrecord(nomfichier) def playsound(nomfichier="C:\\MESSAGE.WAV"): global globalmcison import recordmci globalmcison=recordmci.mci() globalmcison.directsend('open "'+nomfichier+'" alias mamusique') sduree='0' globalmcison.directsend('set mamusique time format milliseconds') err,sduree=globalmcison.directsend('status mamusique length ') #print 'Duree du fichier : ',sduree,' millisecondes' globalmcison.directsend('play mamusique from 0 to '+str(sduree)) return(sduree) def mciplaysound(nomfichier="C:\\MESSAGE.WAV"): global globalmcison import recordmci globalmcison=recordmci.mci() globalmcison.directsend('open "'+nomfichier+'" alias mamusique') sduree='0' globalmcison.directsend('set mamusique time format milliseconds') err,sduree=globalmcison.directsend('status mamusique length ') #print 'Duree du fichier : ',sduree,' millisecondes' globalmcison.directsend('play mamusique from 0 to '+str(sduree)) return(sduree) def mcistopsound(): global globalmcison globalmcison.directsend('stop mamusique') globalmcison.directsend('close mamusique') del globalmcison def mciplayvideo(nomfichier="C:\\cow.mpeg", wintitre="", x=20,y=20, larg=400,haut=300): global globalmcivideo import recordmci sduree='0' if wintitre!='': globalmcivideo=recordmci.mci() globalmcivideo.directsend('open "'+nomfichier+'" alias mavideo') globalmcivideo.directsend('set mavideo time format milliseconds') err,sduree=globalmcivideo.directsend('status mavideo length ') #print 'Duree du fichier : ',sduree,' millisecondes' globalmcivideo.directsend('window mavideo handle '+str(win32gui.FindWindowEx(0,0,0,wintitre))) globalmcivideo.directsend('put mavideo destination at '+str(x)+' '+str(y)+' '+str(larg)+' '+str(haut)) globalmcivideo.directsend('play mavideo from 0 to '+str(sduree)) return(sduree) def mcistopvideo(): global globalmcivideo globalmcivideo.directsend('stop mavideo') globalmcivideo.directsend('close mavideo') del globalmcivideo # # HtmlClipboard ----------------------------------------------------------- # # # http://code.activestate.com/recipes/474121/ (r1) # # An interface to the "HTML Format" clipboard data format #__author__ = "Phillip Piper (jppx1[at]bigfoot.com)" #__date__ = "2006-02-21" #__version__ = "0.1" import re import win32clipboard #--------------------------------------------------------------------------- # Convenience functions to do the most common operation def HasHtml(): """ Return True if there is a Html fragment in the clipboard.. """ cb = HtmlClipboard() return cb.HasHtmlFormat() def GetHtml(): """ Return the Html fragment from the clipboard or None if there is no Html in the clipboard. """ cb = HtmlClipboard() if cb.HasHtmlFormat(): return cb.GetFragment() else: return None def PutHtml(fragment): """ Put the given fragment into the clipboard. Convenience function to do the most common operation """ cb = HtmlClipboard() cb.PutFragment(fragment) #--------------------------------------------------------------------------- class HtmlClipboard: CF_HTML = None MARKER_BLOCK_OUTPUT = \ "Version:1.0\r\n" \ "StartHTML:%09d\r\n" \ "EndHTML:%09d\r\n" \ "StartFragment:%09d\r\n" \ "EndFragment:%09d\r\n" \ "StartSelection:%09d\r\n" \ "EndSelection:%09d\r\n" \ "SourceURL:%s\r\n" MARKER_BLOCK_EX = \ "Version:(\S+)\s+" \ "StartHTML:(\d+)\s+" \ "EndHTML:(\d+)\s+" \ "StartFragment:(\d+)\s+" \ "EndFragment:(\d+)\s+" \ "StartSelection:(\d+)\s+" \ "EndSelection:(\d+)\s+" \ "SourceURL:(\S+)" MARKER_BLOCK_EX_RE = re.compile(MARKER_BLOCK_EX) MARKER_BLOCK = \ "Version:(\S+)\s+" \ "StartHTML:(\d+)\s+" \ "EndHTML:(\d+)\s+" \ "StartFragment:(\d+)\s+" \ "EndFragment:(\d+)\s+" \ "SourceURL:(\S+)" MARKER_BLOCK_RE = re.compile(MARKER_BLOCK) DEFAULT_HTML_BODY = \ "" \ "%s" def __init__(self): self.html = None self.fragment = None self.selection = None self.source = None self.htmlClipboardVersion = None def GetCfHtml(self): """ Return the FORMATID of the HTML format """ if self.CF_HTML is None: self.CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format") return self.CF_HTML def GetAvailableFormats(self): """ Return a possibly empty list of formats available on the clipboard """ formats = [] try: win32clipboard.OpenClipboard(0) cf = win32clipboard.EnumClipboardFormats(0) while (cf != 0): formats.append(cf) cf = win32clipboard.EnumClipboardFormats(cf) finally: win32clipboard.CloseClipboard() return formats def HasHtmlFormat(self): """ Return a boolean indicating if the clipboard has data in HTML format """ return (self.GetCfHtml() in self.GetAvailableFormats()) def GetFromClipboard(self): """ Read and decode the HTML from the clipboard """ try: win32clipboard.OpenClipboard(0) src = win32clipboard.GetClipboardData(self.GetCfHtml()) #print src self.DecodeClipboardSource(src) finally: win32clipboard.CloseClipboard() def DecodeClipboardSource(self, src): """ Decode the given string to figure out the details of the HTML that's on the string """ # Try the extended format first (which has an explicit selection) matches = self.MARKER_BLOCK_EX_RE.match(src) if matches: self.prefix = matches.group(0) self.htmlClipboardVersion = matches.group(1) self.html = src[int(matches.group(2)):int(matches.group(3))] self.fragment = src[int(matches.group(4)):int(matches.group(5))] self.selection = src[int(matches.group(6)):int(matches.group(7))] self.source = matches.group(8) else: # Failing that, try the version without a selection matches = self.MARKER_BLOCK_RE.match(src) if matches: self.prefix = matches.group(0) self.htmlClipboardVersion = matches.group(1) self.html = src[int(matches.group(2)):int(matches.group(3))] self.fragment = src[int(matches.group(4)):int(matches.group(5))] self.source = matches.group(6) self.selection = self.fragment def GetHtml(self, refresh=False): """ Return the entire Html document """ if not self.html or refresh: self.GetFromClipboard() return self.html def GetFragment(self, refresh=False): """ Return the Html fragment. A fragment is well-formated HTML enclosing the selected text """ if not self.fragment or refresh: self.GetFromClipboard() return self.fragment def GetSelection(self, refresh=False): """ Return the part of the HTML that was selected. It might not be well-formed. """ if not self.selection or refresh: self.GetFromClipboard() return self.selection def GetSource(self, refresh=False): """ Return the URL of the source of this HTML """ if not self.selection or refresh: self.GetFromClipboard() return self.source def PutFragment(self, fragment, selection=None, html=None, source=None): """ Put the given well-formed fragment of Html into the clipboard. selection, if given, must be a literal string within fragment. html, if given, must be a well-formed Html document that textually contains fragment and its required markers. """ if selection is None: selection = fragment if html is None: html = self.DEFAULT_HTML_BODY % fragment if source is None: source = "file://HtmlClipboard.py" fragmentStart = html.index(fragment) fragmentEnd = fragmentStart + len(fragment) selectionStart = html.index(selection) selectionEnd = selectionStart + len(selection) self.PutToClipboard(html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source) def PutToClipboard(self, html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source="None"): """ Replace the Clipboard contents with the given html information. """ try: win32clipboard.OpenClipboard(0) win32clipboard.EmptyClipboard() src = self.EncodeClipboardSource(html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source) #print 284,src win32clipboard.SetClipboardData(self.GetCfHtml(), src) finally: win32clipboard.CloseClipboard() def EncodeClipboardSource(self, html, fragmentStart, fragmentEnd, selectionStart, selectionEnd, source): """ Join all our bits of information into a string formatted as per the HTML format specs. """ # How long is the prefix going to be? dummyPrefix = self.MARKER_BLOCK_OUTPUT % (0, 0, 0, 0, 0, 0, source) lenPrefix = len(dummyPrefix) prefix = self.MARKER_BLOCK_OUTPUT % (lenPrefix, len(html)+lenPrefix, fragmentStart+lenPrefix, fragmentEnd+lenPrefix, selectionStart+lenPrefix, selectionEnd+lenPrefix, source) return (prefix + html) def DumpHtml(): cb = HtmlClipboard() print "GetAvailableFormats()=%s" % str(cb.GetAvailableFormats()) print "HasHtmlFormat()=%s" % str(cb.HasHtmlFormat()) if cb.HasHtmlFormat(): cb.GetFromClipboard() print "prefix=>>>%s<<>>%s<<>>%s<<>>%s<<>>%s<<>>%s<<17: if win32clipboard.GetClipboardFormatName(enum) == chaineid: format=enum break else: if enum==chaineid: format=enum break finally: pass if format is None: #return(None,chaineid,enum,'') return data = None #win32clipboard.CloseClipboard() #win32clipboard.OpenClipboard() #print 3728,format try: data = win32clipboard.GetClipboardData(format) except: #print "Pb : le clipboard n'est pas lisible, n'est pas dans le bon format, ou est vide." pass win32clipboard.CloseClipboard() #return format,chaineid,data return data #*** MODIF *** valeurs par défaut, suppression d'un paramètre def clipboard_set(chaineformat=win32clipboard.CF_TEXT, data=None): if data is None: data=GlobalPARAM[0] win32clipboard.OpenClipboard() format = None try: enum = 0 while 1: enum = win32clipboard.EnumClipboardFormats(enum) if enum==0: break if enum>17: if win32clipboard.GetClipboardFormatName(enum) == chaineformat: format=enum break else: if enum==chaineformat: format=enum break finally: pass if format is None: format=win32clipboard.RegisterClipboardFormat(chaineformat) #"Rich Text Format") #return try: ###win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(format,data) #print "format Clip",format except: #msginfo("Pb "+"avec"+" Set",format) pass win32clipboard.CloseClipboard() """ Clipboard exemples : ------------------ clpformat,clpchaine,clpdata=clipboard_get('Rich Text Format') 'Rich Text Format' 'Borland Form Object' win32clipboard.CF_TEXT win32clipboard.CF_BITMAP win32clipboard.CF_METAFILEPICT win32clipboard.CF_SYLK win32clipboard.CF_DIF win32clipboard.CF_TIFF win32clipboard.CF_OEMTEXT win32clipboard.CF_DIB win32clipboard.CF_PALETTE win32clipboard.CF_PENDATA win32clipboard.CF_RIFF win32clipboard.CF_WAVE win32clipboard.CF_UNICODETEXT win32clipboard.CF_ENHMETAFILE win32clipboard.CF_HDROP win32clipboard.CF_LOCALE win32con.CF_TEXT win32con.CF_BITMAP win32con.CF_METAFILEPICT win32con.CF_SYLK win32con.CF_DIF win32con.CF_TIFF win32con.CF_OEMTEXT win32con.CF_DIB win32con.CF_PALETTE win32con.CF_PENDATA win32con.CF_RIFF win32con.CF_WAVE win32con.CF_UNICODETEXT win32con.CF_ENHMETAFILE win32con.CF_HDROP win32con.CF_LOCALE win32con.CF_RTF CF_BITMAP ne fonctionne pas à tester : 'RTF in UTF8' 'Ole Private Data' 'RTF As Text' print clpformat,clpchaine,len(clpdata) f=open("ess.jpg","wb") f.write(clpdata) f.close() exemples : clipboard_set(win32con.CF_TEXT,exempledata) print ponx.clipboard_get(win32con.CF_TEXT) """ #*** NEW/MODIF v2.37 ; 27.07.05*** def clipboardtxt(chaine=None): global chaineretour import win32clipboard,win32con try: win32clipboard.OpenClipboard() if chaine is None: try: chaine=win32clipboard.GetClipboardData(win32con.CF_TEXT) #win32clipboard.EmptyClipboard() #win32clipboard.SetClipboardText(chaine) chaineretour=chaine return(chaine) except: chaineretour='' return('') else: try: win32clipboard.EmptyClipboard() time.sleep(0.05) win32clipboard.SetClipboardText(chaine) except: pass except: pass try: win32clipboard.CloseClipboard() except: pass """ def screenshot2(filename='c:\\screenshot.bmp'): import wxPython.wx screenDC, memDC = wxPython.wx.wxScreenDC(), wxPython.wx.wxMemoryDC() # device contexts width, height = screenDC.GetSizeTuple() # screen size bitmap = wxPython.wx.wxEmptyBitmap(width, height) # create bitmap memDC.SelectObject(bitmap) # select bitmap memDC.Blit(0, 0, width, height, screenDC, 0, 0) # copy screen bitmap.SaveFile(filename, wxPython.wx.wxBITMAP_TYPE_BMP) # save bitmap """ def screenshot(filename='c:\\screenshot.bmp'): import Image, ImageGrab, ImageFont, ImageDraw ImageGrab.grab().save(filename) #*** v.3.15 ; 20.02.06 ; possibilité de passer la paramètre postai comme une chaîne (mieux pour Ponx-dynamique) def screenshotplus(filename='c:\\screenshot.bmp', postai=[], taille=67, txt="PONX",txtx=40,txty=10,police="arial.ttf",ftaille=42,fcolor="#ff2200", ombrage="OUI", filetampon="c:\\dev\\python\\ponx.jpg",tamponx=1,tampony=1 ): """ paramètres de screenshotplus() : nom du fichier de sortie (l'extension détermine le type/format graphique) [ X, Y, Largeur, Hauteur] position et taille de l'image capturée redimensionnement, en % Texte à écrire sur la capture Position_X du texte écrit Position_Y du texte écrit Fonte utilisée pour écrire (True-type seulement) Taille de la police Couleur de la police (en hexadécimal) Doit-on apposer un tampon ? fichier (graphique) tampon Position_X du tampon Position_Y du tampon """ global chaineretour import Image, ImageGrab, ImageFont, ImageDraw img =ImageGrab.grab() postai=eval(str(postai)) #msginfo("postai",str(postai)) if postai<>[]: img = img.crop((int(postai[0]),int(postai[1]),int(postai[2]),int(postai[3]))) if taille<>100: x,y = img.size x = x*taille//100 y = y*taille//100 img = img.resize((x,y)) fonttf = ImageFont.truetype(police,ftaille) draw = ImageDraw.Draw(img) if string.upper(ombrage)=="OUI": draw.text((txtx+2, txty+2), txt,font=fonttf,fill="#000000") draw.text((txtx, txty), txt,font=fonttf,fill=fcolor) if filetampon<>"": tampon = Image.open(filetampon) img.paste(tampon,(tamponx,tampony)) img.save(filename) chaineretour=filename #img.show() def ponxzip(commande, dossier, fichierzip, listfichiers): if dossier!='': os.chdir(dossier) if commande=="T" or commande=="t": flag='OK' try: z=zipfile.ZipFile(dossier+'\\'+fichierzip,"r") for chaque in z.namelist(): try: bof=z.read(chaque) except: flag='Pb dans le contenu' except: flag=_('Pb Global') vifi(flag) #*** modif 28.04.2006 : 3.206 ; double-retour *** def recupweb(adr): page = urllib2.urlopen(adr).read() vifi(page) return page #*** Modif *** ajout paramètre "fichier" def recupfileweb(adr, repenregistrement='C:\\', fichier=None): #repenregistrement : exemple : C:\\WebFil\\ if not repenregistrement.endswith('\\'): repenregistrement+='\\' #msginfo(repenregistrement,adr) try: page = urllib2.urlopen(adr).read() list = string.split(adr,'/') except: return if fichier is None: nomlocal=list[-1] else: nomlocal=fichier #msginfo("sto2",repenregistrement+nomlocal) f = open(repenregistrement+nomlocal, "wb") f.write(page) f.close() #vifi(_('Fichier ')+repenregistrement+nomlocal+_(' téléchargé depuis ')+adr) vifi(_('Fichier ')+str(len(page))+repenregistrement+nomlocal+_(' telecharge depuis ')+adr) def recupdezipweb(adr, rep): page = urllib2.urlopen(adr).read() f = open(rep+'\\ponxtmp.zip', "wb") f.write(page) f.close() z = zipfile.ZipFile(rep+'\\ponxtmp.zip',"r") for filename in z.namelist(): if filename[-3:]=='fsl' or filename[-3:]=='FSL' or filename[-3:]=='fdl' or filename[-3:]=='FDL': str=filename bytes = z.read(filename) f = open(rep+'\\'+filename, "wb") f.write(bytes) f.close() os.remove(rep+'\\ponxtmp.zip') vifi(str) #*** NEW *** def u1252(chu): try: if type(chu) is unicode: return chu.encode('cp1252','replace') else: return chu except: return repr(chu) #*** NEW *** def uutf8(chu): try: if type(chu) is unicode: return chu.encode('utf-8','replace') else: return chu except: try: return repr(chu).encode('utf-8','replace') except: return repr(chu) #***new: 3.235 ; 12.12.2006 *** def utf8inansi(ch=''): if ch=='': ch=GlobalPARAM[0].encode('cp1252','replace') chaineretour=ch.decode('cp1252').encode('utf-8') return chaineretour #***new: 3.235 ; 12.12.2006 *** def utf8fromansi(ch=''): if ch=='': ch=GlobalPARAM[0] chaineretour=ch.decode('utf-8') return chaineretour mappinghighascii = { chr(0):'', chr(1):'', chr(2):'', chr(3):'', chr(4):'', chr(5):'', chr(6):'', chr(7):'', chr(8):'', chr(9):'', chr(10):'', chr(11):'', chr(12):'', chr(13):'', chr(14):'', chr(15):'', chr(16):'', chr(17):'', chr(18):'', chr(19):'', chr(20):'', chr(21):'', chr(22):'', chr(23):'', chr(24):'', chr(25):'', chr(26):'', chr(27):'', chr(28):'', chr(29):'', chr(30):'', chr(31):'', chr(32):chr(32), chr(33):chr(33), chr(34):chr(34), chr(35):chr(35), chr(36):chr(36), chr(37):chr(37), chr(38):chr(38), chr(39):chr(39), chr(40):chr(40), chr(41):chr(41), chr(42):chr(42), chr(43):chr(43), chr(44):chr(44), chr(45):chr(45), chr(46):chr(46), chr(47):chr(47), chr(48):chr(48), chr(49):chr(49), chr(50):chr(50), chr(51):chr(51), chr(52):chr(52), chr(53):chr(53), chr(54):chr(54), chr(55):chr(55), chr(56):chr(56), chr(57):chr(57), chr(58):chr(58), chr(59):chr(59), chr(60):chr(60), chr(61):chr(61), chr(62):chr(62), chr(63):chr(63), chr(64):chr(64), chr(65):chr(65), chr(66):chr(66), chr(67):chr(67), chr(68):chr(68), chr(69):chr(69), chr(70):chr(70), chr(71):chr(71), chr(72):chr(72), chr(73):chr(73), chr(74):chr(74), chr(75):chr(75), chr(76):chr(76), chr(77):chr(77), chr(78):chr(78), chr(79):chr(79), chr(80):chr(80), chr(81):chr(81), chr(82):chr(82), chr(83):chr(83), chr(84):chr(84), chr(85):chr(85), chr(86):chr(86), chr(87):chr(87), chr(88):chr(88), chr(89):chr(89), chr(90):chr(90), chr(91):chr(91), chr(92):chr(92), chr(93):chr(93), chr(94):chr(94), chr(95):chr(95), chr(96):chr(96), chr(97):chr(97), chr(98):chr(98), chr(99):chr(99), chr(100):chr(100), chr(101):chr(101), chr(102):chr(102), chr(103):chr(103), chr(104):chr(104), chr(105):chr(105), chr(106):chr(106), chr(107):chr(107), chr(108):chr(108), chr(109):chr(109), chr(110):chr(110), chr(111):chr(111), chr(112):chr(112), chr(113):chr(113), chr(114):chr(114), chr(115):chr(115), chr(116):chr(116), chr(117):chr(117), chr(118):chr(118), chr(119):chr(119), chr(120):chr(120), chr(121):chr(121), chr(122):chr(122), chr(123):chr(123), chr(124):chr(124), chr(125):chr(125), chr(126):chr(126), chr(127):chr(127), chr(128):chr(128), chr(129):chr(129), chr(130):chr(130), chr(131):chr(131), chr(132):chr(132), chr(133):chr(133), chr(134):chr(134), chr(135):chr(135), chr(136):chr(136), chr(137):chr(137), chr(138):chr(138), chr(139):chr(139), chr(140):chr(140), chr(141):chr(141), chr(142):chr(142), chr(143):chr(143), chr(144):chr(144), chr(145):chr(145), chr(146):chr(146), chr(147):chr(147), chr(148):chr(148), chr(149):chr(149), chr(150):chr(150), chr(151):chr(151), chr(152):chr(152), chr(153):chr(153), chr(154):chr(154), chr(155):chr(155), chr(156):chr(156), chr(157):chr(157), chr(158):chr(158), chr(159):chr(159), chr(160):chr(160), chr(161):chr(161), chr(162):chr(162), chr(163):chr(163), chr(164):chr(164), chr(165):chr(165), chr(166):chr(166), chr(167):chr(167), chr(168):chr(168), chr(169):chr(169), chr(170):chr(170), chr(171):chr(171), chr(172):chr(172), chr(173):chr(173), chr(174):chr(174), chr(175):chr(175), chr(176):chr(176), chr(177):chr(177), chr(178):chr(178), chr(179):chr(179), chr(180):chr(180), chr(181):chr(181), chr(182):chr(182), chr(183):chr(183), chr(184):chr(184), chr(185):chr(185), chr(186):chr(186), chr(187):chr(187), chr(188):chr(188), chr(189):chr(189), chr(190):chr(190), chr(191):chr(191), chr(192):chr(192), chr(193):chr(193), chr(194):chr(194), chr(195):chr(195), chr(196):chr(196), chr(197):chr(197), chr(198):chr(198), chr(199):chr(199), chr(200):chr(200), chr(201):chr(201), chr(202):chr(202), chr(203):chr(203), chr(204):chr(204), chr(205):chr(205), chr(206):chr(206), chr(207):chr(207), chr(208):chr(208), chr(209):chr(209), chr(210):chr(210), chr(211):chr(211), chr(212):chr(212), chr(213):chr(213), chr(214):chr(214), chr(215):chr(215), chr(216):chr(216), chr(217):chr(217), chr(218):chr(218), chr(219):chr(219), chr(220):chr(220), chr(221):chr(221), chr(222):chr(222), chr(223):chr(223), chr(224):chr(224), chr(225):chr(225), chr(226):chr(226), chr(227):chr(227), chr(228):chr(228), chr(229):chr(229), chr(230):chr(230), chr(231):chr(231), chr(232):chr(232), chr(233):chr(233), chr(234):chr(234), chr(235):chr(235), chr(236):chr(236), chr(237):chr(237), chr(238):chr(238), chr(239):chr(239), chr(240):chr(240), chr(241):chr(241), chr(242):chr(242), chr(243):chr(243), chr(244):chr(244), chr(245):chr(245), chr(246):chr(246), chr(247):chr(247), chr(248):chr(248), chr(249):chr(249), chr(250):chr(250), chr(251):chr(251), chr(252):chr(252), chr(253):chr(253), chr(254):chr(254), chr(255):chr(255) } mappingtoutascii = { chr(0):chr(0), chr(1):chr(1), chr(2):chr(2), chr(3):chr(3), chr(4):chr(4), chr(5):chr(5), chr(6):chr(6), chr(7):chr(7), chr(8):chr(8), chr(9):chr(9), chr(10):chr(10), chr(11):chr(11), chr(12):chr(12), chr(13):chr(13), chr(14):chr(14), chr(15):chr(15), chr(16):chr(16), chr(17):chr(17), chr(18):chr(18), chr(19):chr(19), chr(20):chr(20), chr(21):chr(21), chr(22):chr(22), chr(23):chr(23), chr(24):chr(24), chr(25):chr(25), chr(26):chr(26), chr(27):chr(27), chr(28):chr(28), chr(29):chr(29), chr(30):chr(30), chr(31):chr(31), chr(32):chr(32), chr(33):chr(33), chr(34):chr(34), chr(35):chr(35), chr(36):chr(36), chr(37):chr(37), chr(38):chr(38), chr(39):chr(39), chr(40):chr(40), chr(41):chr(41), chr(42):chr(42), chr(43):chr(43), chr(44):chr(44), chr(45):chr(45), chr(46):chr(46), chr(47):chr(47), chr(48):chr(48), chr(49):chr(49), chr(50):chr(50), chr(51):chr(51), chr(52):chr(52), chr(53):chr(53), chr(54):chr(54), chr(55):chr(55), chr(56):chr(56), chr(57):chr(57), chr(58):chr(58), chr(59):chr(59), chr(60):chr(60), chr(61):chr(61), chr(62):chr(62), chr(63):chr(63), chr(64):chr(64), chr(65):chr(65), chr(66):chr(66), chr(67):chr(67), chr(68):chr(68), chr(69):chr(69), chr(70):chr(70), chr(71):chr(71), chr(72):chr(72), chr(73):chr(73), chr(74):chr(74), chr(75):chr(75), chr(76):chr(76), chr(77):chr(77), chr(78):chr(78), chr(79):chr(79), chr(80):chr(80), chr(81):chr(81), chr(82):chr(82), chr(83):chr(83), chr(84):chr(84), chr(85):chr(85), chr(86):chr(86), chr(87):chr(87), chr(88):chr(88), chr(89):chr(89), chr(90):chr(90), chr(91):chr(91), chr(92):chr(92), chr(93):chr(93), chr(94):chr(94), chr(95):chr(95), chr(96):chr(96), chr(97):chr(97), chr(98):chr(98), chr(99):chr(99), chr(100):chr(100), chr(101):chr(101), chr(102):chr(102), chr(103):chr(103), chr(104):chr(104), chr(105):chr(105), chr(106):chr(106), chr(107):chr(107), chr(108):chr(108), chr(109):chr(109), chr(110):chr(110), chr(111):chr(111), chr(112):chr(112), chr(113):chr(113), chr(114):chr(114), chr(115):chr(115), chr(116):chr(116), chr(117):chr(117), chr(118):chr(118), chr(119):chr(119), chr(120):chr(120), chr(121):chr(121), chr(122):chr(122), chr(123):chr(123), chr(124):chr(124), chr(125):chr(125), chr(126):chr(126), chr(127):chr(127), chr(128):chr(128), chr(129):chr(129), chr(130):chr(130), chr(131):chr(131), chr(132):chr(132), chr(133):chr(133), chr(134):chr(134), chr(135):chr(135), chr(136):chr(136), chr(137):chr(137), chr(138):chr(138), chr(139):chr(139), chr(140):chr(140), chr(141):chr(141), chr(142):chr(142), chr(143):chr(143), chr(144):chr(144), chr(145):chr(145), chr(146):chr(146), chr(147):chr(147), chr(148):chr(148), chr(149):chr(149), chr(150):chr(150), chr(151):chr(151), chr(152):chr(152), chr(153):chr(153), chr(154):chr(154), chr(155):chr(155), chr(156):chr(156), chr(157):chr(157), chr(158):chr(158), chr(159):chr(159), chr(160):chr(160), chr(161):chr(161), chr(162):chr(162), chr(163):chr(163), chr(164):chr(164), chr(165):chr(165), chr(166):chr(166), chr(167):chr(167), chr(168):chr(168), chr(169):chr(169), chr(170):chr(170), chr(171):chr(171), chr(172):chr(172), chr(173):chr(173), chr(174):chr(174), chr(175):chr(175), chr(176):chr(176), chr(177):chr(177), chr(178):chr(178), chr(179):chr(179), chr(180):chr(180), chr(181):chr(181), chr(182):chr(182), chr(183):chr(183), chr(184):chr(184), chr(185):chr(185), chr(186):chr(186), chr(187):chr(187), chr(188):chr(188), chr(189):chr(189), chr(190):chr(190), chr(191):chr(191), chr(192):chr(192), chr(193):chr(193), chr(194):chr(194), chr(195):chr(195), chr(196):chr(196), chr(197):chr(197), chr(198):chr(198), chr(199):chr(199), chr(200):chr(200), chr(201):chr(201), chr(202):chr(202), chr(203):chr(203), chr(204):chr(204), chr(205):chr(205), chr(206):chr(206), chr(207):chr(207), chr(208):chr(208), chr(209):chr(209), chr(210):chr(210), chr(211):chr(211), chr(212):chr(212), chr(213):chr(213), chr(214):chr(214), chr(215):chr(215), chr(216):chr(216), chr(217):chr(217), chr(218):chr(218), chr(219):chr(219), chr(220):chr(220), chr(221):chr(221), chr(222):chr(222), chr(223):chr(223), chr(224):chr(224), chr(225):chr(225), chr(226):chr(226), chr(227):chr(227), chr(228):chr(228), chr(229):chr(229), chr(230):chr(230), chr(231):chr(231), chr(232):chr(232), chr(233):chr(233), chr(234):chr(234), chr(235):chr(235), chr(236):chr(236), chr(237):chr(237), chr(238):chr(238), chr(239):chr(239), chr(240):chr(240), chr(241):chr(241), chr(242):chr(242), chr(243):chr(243), chr(244):chr(244), chr(245):chr(245), chr(246):chr(246), chr(247):chr(247), chr(248):chr(248), chr(249):chr(249), chr(250):chr(250), chr(251):chr(251), chr(252):chr(252), chr(253):chr(253), chr(254):chr(254), chr(255):chr(255) } mappingcharmin = { chr(127):' ', chr(128):'E', chr(129):'.', chr(130):',', chr(131):'f', chr(132):'"', chr(133):'.', chr(134):'+', chr(135):'+', chr(137):'%', chr(138):'S', chr(139):'<', chr(140):'O', chr(141):'.', chr(142):'Z', chr(143):'.', chr(144):'.', chr(145):'\'', chr(146):'\'', chr(147):'"', chr(148):'"', chr(149):'.', chr(150):'-', chr(151):'_', chr(152):'-', chr(153):'.', chr(154):'s', chr(155):'>', chr(156):'o', chr(157):'.', chr(158):'z', chr(159):'Y', chr(160):'.', chr(161):'i', chr(162):'c', chr(163):'L', chr(164):'+', chr(165):'y', chr(166):'|', chr(167):'S', chr(168):'¨', chr(169):'c', chr(170):'a', chr(171):'<', chr(172):'.', chr(173):'-', chr(174):'r', chr(175):'-', chr(176):'o', chr(177):'+', chr(178):'2', chr(179):'3', chr(180):'\'', chr(181):'u', chr(182):'.', chr(183):'.', chr(184):',', chr(185):'1', chr(186):'o', chr(187):'>', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'?', chr(192):'A', chr(193):'A', chr(194):'A', chr(195):'A', chr(196):'A', chr(197):'A', chr(198):'A', chr(199):'C', chr(200):'E', chr(201):'E', chr(202):'E', chr(203):'E', chr(204):'I', chr(205):'I', chr(206):'I', chr(207):'I', chr(208):'D', chr(209):'N', chr(210):'O', chr(211):'O', chr(212):'O', chr(213):'O', chr(214):'O', chr(215):'x', chr(216):'O', chr(217):'U', chr(218):'U', chr(219):'U', chr(220):'U', chr(221):'Y', chr(222):'P', chr(223):'b', chr(224):'a', chr(225):'a', chr(226):'a', chr(227):'a', chr(228):'a', chr(229):'a', chr(230):'a', chr(231):'c', chr(232):'e', chr(233):'e', chr(234):'e', chr(235):'e', chr(236):'i', chr(237):'i', chr(238):'i', chr(239):'i', chr(240):'o', chr(241):'n', chr(242):'o', chr(243):'o', chr(244):'o', chr(245):'o', chr(246):'o', chr(247):'+', chr(248):'o', chr(249):'u', chr(250):'u', chr(251):'u', chr(252):'u', chr(253):'y', chr(254):'b', chr(255):'y'} mappingcharmaj = { chr(97):'A', chr(98):'B', chr(99):'C', chr(100):'D', chr(101):'E', chr(102):'F', chr(103):'G', chr(104):'H', chr(105):'I', chr(106):'J', chr(107):'K', chr(108):'L', chr(109):'M', chr(110):'N', chr(111):'O', chr(112):'P', chr(113):'Q', chr(114):'R', chr(115):'S', chr(116):'T', chr(117):'U', chr(118):'V', chr(119):'W', chr(120):'X', chr(121):'Y', chr(122):'Z', chr(127):' ', chr(128):'E', chr(129):'.', chr(130):',', chr(131):'F', chr(132):'"', chr(133):'.', chr(134):'+', chr(135):'+', chr(137):'%', chr(138):'S', chr(139):'<', chr(140):'O', chr(141):'.', chr(142):'Z', chr(143):'.', chr(144):'.', chr(145):'\'', chr(146):'\'', chr(147):'"', chr(148):'"', chr(149):'.', chr(150):'-', chr(151):'_', chr(152):'-', chr(153):'.', chr(154):'S', chr(155):'>', chr(156):'O', chr(157):'.', chr(158):'Z', chr(159):'Y', chr(160):'.', chr(161):'I', chr(162):'C', chr(163):'L', chr(164):'+', chr(165):'Y', chr(166):'|', chr(167):'S', chr(168):'¨', chr(169):'C', chr(170):'A', chr(171):'<', chr(172):'.', chr(173):'-', chr(174):'R', chr(175):'-', chr(176):'O', chr(177):'+', chr(178):'2', chr(179):'3', chr(180):'\'', chr(181):'U', chr(182):'.', chr(183):'.', chr(184):',', chr(185):'1', chr(186):'O', chr(187):'>', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'?', chr(192):'A', chr(193):'A', chr(194):'A', chr(195):'A', chr(196):'A', chr(197):'A', chr(198):'A', chr(199):'C', chr(200):'E', chr(201):'E', chr(202):'E', chr(203):'E', chr(204):'I', chr(205):'I', chr(206):'I', chr(207):'I', chr(208):'D', chr(209):'N', chr(210):'O', chr(211):'O', chr(212):'O', chr(213):'O', chr(214):'O', chr(215):'X', chr(216):'O', chr(217):'U', chr(218):'U', chr(219):'U', chr(220):'U', chr(221):'Y', chr(222):'P', chr(223):'B', chr(224):'A', chr(225):'A', chr(226):'A', chr(227):'A', chr(228):'A', chr(229):'A', chr(230):'A', chr(231):'C', chr(232):'E', chr(233):'E', chr(234):'E', chr(235):'E', chr(236):'I', chr(237):'I', chr(238):'I', chr(239):'I', chr(240):'O', chr(241):'N', chr(242):'O', chr(243):'O', chr(244):'O', chr(245):'O', chr(246):'O', chr(247):'+', chr(248):'O', chr(249):'U', chr(250):'U', chr(251):'U', chr(252):'U', chr(253):'Y', chr(254):'B', chr(255):'Y'} mappingcharlettr = { chr(32):'', chr(33):'', chr(34):'', chr(35):'', chr(36):'S', chr(37):'', chr(38):'', chr(39):'', chr(40):'', chr(41):'', chr(42):'', chr(43):'', chr(44):'', chr(45):'', chr(46):'', chr(47):'', chr(48):'', chr(58):'', chr(59):'', chr(60):'', chr(61):'', chr(62):'', chr(63):'', chr(64):'', chr(91):'', chr(92):'', chr(93):'', chr(94):'', chr(95):'', chr(96):'', chr(97):'A', chr(98):'B', chr(99):'C', chr(100):'D', chr(101):'E', chr(102):'F', chr(103):'G', chr(104):'H', chr(105):'I', chr(106):'J', chr(107):'K', chr(108):'L', chr(109):'M', chr(110):'N', chr(111):'O', chr(112):'P', chr(113):'Q', chr(114):'R', chr(115):'S', chr(116):'T', chr(117):'U', chr(118):'V', chr(119):'W', chr(120):'X', chr(121):'Y', chr(122):'Z', chr(123):'', chr(124):'', chr(125):'', chr(126):'', chr(127):'', chr(128):'E', chr(129):'', chr(130):'', chr(131):'F', chr(132):'', chr(133):'', chr(134):'', chr(135):'', chr(137):'', chr(138):'S', chr(139):'', chr(140):'O', chr(141):'', chr(142):'Z', chr(143):'', chr(144):'', chr(145):'', chr(146):'', chr(147):'', chr(148):'', chr(149):'', chr(150):'', chr(151):'', chr(152):'', chr(153):'', chr(154):'S', chr(155):'', chr(156):'O', chr(157):'', chr(158):'Z', chr(159):'Y', chr(160):'', chr(161):'I', chr(162):'C', chr(163):'L', chr(164):'', chr(165):'Y', chr(166):'', chr(167):'S', chr(168):'', chr(169):'C', chr(170):'A', chr(171):'', chr(172):'', chr(173):'', chr(174):'R', chr(175):'', chr(176):'O', chr(177):'', chr(178):'2', chr(179):'3', chr(180):'', chr(181):'U', chr(182):'', chr(183):'', chr(184):'', chr(185):'1', chr(186):'O', chr(187):'', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'', chr(192):'A', chr(193):'A', chr(194):'A', chr(195):'A', chr(196):'A', chr(197):'A', chr(198):'A', chr(199):'C', chr(200):'E', chr(201):'E', chr(202):'E', chr(203):'E', chr(204):'I', chr(205):'I', chr(206):'I', chr(207):'I', chr(208):'D', chr(209):'N', chr(210):'O', chr(211):'O', chr(212):'O', chr(213):'O', chr(214):'O', chr(215):'X', chr(216):'O', chr(217):'U', chr(218):'U', chr(219):'U', chr(220):'U', chr(221):'Y', chr(222):'P', chr(223):'B', chr(224):'A', chr(225):'A', chr(226):'A', chr(227):'A', chr(228):'A', chr(229):'A', chr(230):'A', chr(231):'C', chr(232):'E', chr(233):'E', chr(234):'E', chr(235):'E', chr(236):'I', chr(237):'I', chr(238):'I', chr(239):'I', chr(240):'O', chr(241):'N', chr(242):'O', chr(243):'O', chr(244):'O', chr(245):'O', chr(246):'O', chr(247):'', chr(248):'O', chr(249):'U', chr(250):'U', chr(251):'U', chr(252):'U', chr(253):'Y', chr(254):'B', chr(255):'Y'} mappingcharnum = { chr(1):'', chr(2):'', chr(3):'', chr(4):'', chr(5):'', chr(6):'', chr(7):'', chr(8):'', chr(9):'', chr(10):'', chr(11):'', chr(12):'', chr(13):'', chr(14):'', chr(15):'', chr(16):'', chr(17):'', chr(18):'', chr(19):'', chr(20):'', chr(21):'', chr(22):'', chr(23):'', chr(24):'', chr(25):'', chr(26):'', chr(27):'', chr(28):'', chr(29):'', chr(30):'', chr(31):'', chr(32):'', chr(33):'', chr(34):'', chr(35):'', chr(36):'', chr(37):'', chr(38):'', chr(39):'', chr(40):'', chr(41):'', chr(42):'', chr(43):'', chr(44):'.', chr(45):'', chr(46):'.', chr(47):'', chr(48):'0', chr(49):'1', chr(50):'2', chr(51):'3', chr(52):'4', chr(53):'5', chr(54):'6', chr(55):'7', chr(56):'8', chr(57):'9', chr(58):'', chr(59):'', chr(60):'', chr(61):'', chr(62):'', chr(63):'', chr(64):'', chr(65):'', chr(66):'', chr(67):'', chr(68):'', chr(69):'', chr(70):'', chr(71):'', chr(72):'', chr(73):'', chr(74):'', chr(75):'', chr(76):'', chr(77):'', chr(78):'', chr(79):'', chr(80):'', chr(81):'', chr(82):'', chr(83):'', chr(84):'', chr(85):'', chr(86):'', chr(87):'', chr(88):'', chr(89):'', chr(90):'', chr(91):'', chr(92):'', chr(93):'', chr(94):'', chr(95):'', chr(96):'', chr(97):'', chr(98):'', chr(99):'', chr(100):'', chr(101):'', chr(102):'', chr(103):'', chr(104):'', chr(105):'', chr(106):'', chr(107):'', chr(108):'', chr(109):'', chr(110):'', chr(111):'', chr(112):'', chr(113):'', chr(114):'', chr(115):'', chr(116):'', chr(117):'', chr(118):'', chr(119):'', chr(120):'', chr(121):'', chr(122):'', chr(123):'', chr(124):'', chr(125):'', chr(126):'', chr(127):'', chr(128):'', chr(129):'', chr(130):'', chr(131):'', chr(132):'', chr(133):'', chr(134):'', chr(135):'', chr(137):'', chr(138):'', chr(139):'', chr(140):'', chr(141):'', chr(142):'', chr(143):'', chr(144):'', chr(145):'', chr(146):'', chr(147):'', chr(148):'', chr(149):'', chr(150):'', chr(151):'', chr(152):'', chr(153):'', chr(154):'', chr(155):'', chr(156):'', chr(157):'', chr(158):'', chr(159):'', chr(160):'', chr(161):'', chr(162):'', chr(163):'', chr(164):'', chr(165):'', chr(166):'', chr(167):'', chr(168):'', chr(169):'', chr(170):'', chr(171):'', chr(172):'', chr(173):'', chr(174):'', chr(175):'', chr(176):'', chr(177):'', chr(178):'', chr(179):'', chr(180):'', chr(181):'', chr(182):'', chr(183):'', chr(184):'', chr(185):'', chr(186):'', chr(187):'', chr(188):'', chr(189):'', chr(190):'', chr(191):'', chr(192):'', chr(193):'', chr(194):'', chr(195):'', chr(196):'', chr(197):'', chr(198):'', chr(199):'', chr(200):'', chr(201):'', chr(202):'', chr(203):'', chr(204):'', chr(205):'', chr(206):'', chr(207):'', chr(208):'', chr(209):'', chr(210):'', chr(211):'', chr(212):'', chr(213):'', chr(214):'', chr(215):'', chr(216):'', chr(217):'', chr(218):'', chr(219):'', chr(220):'', chr(221):'', chr(222):'', chr(223):'', chr(224):'', chr(225):'', chr(226):'', chr(227):'', chr(228):'', chr(229):'', chr(230):'', chr(231):'', chr(232):'', chr(233):'', chr(234):'', chr(235):'', chr(236):'', chr(237):'', chr(238):'', chr(239):'', chr(240):'', chr(241):'', chr(242):'', chr(243):'', chr(244):'', chr(245):'', chr(246):'', chr(247):'', chr(248):'', chr(249):'', chr(250):'', chr(251):'', chr(252):'', chr(253):'', chr(254):'', chr(255):''} mappingcharnumber = { chr(1):'', chr(2):'', chr(3):'', chr(4):'', chr(5):'', chr(6):'', chr(7):'', chr(8):'', chr(9):'', chr(10):'', chr(11):'', chr(12):'', chr(13):'', chr(14):'', chr(15):'', chr(16):'', chr(17):'', chr(18):'', chr(19):'', chr(20):'', chr(21):'', chr(22):'', chr(23):'', chr(24):'', chr(25):'', chr(26):'', chr(27):'', chr(28):'', chr(29):'', chr(30):'', chr(31):'', chr(32):'', chr(33):'', chr(34):'', chr(35):'', chr(36):'', chr(37):'', chr(38):'', chr(39):'', chr(40):'', chr(41):'', chr(42):'', chr(43):'', chr(44):'.', chr(45):'.', chr(46):'.', chr(47):'.', chr(48):'0', chr(49):'1', chr(50):'2', chr(51):'3', chr(52):'4', chr(53):'5', chr(54):'6', chr(55):'7', chr(56):'8', chr(57):'9', chr(58):'', chr(59):'', chr(60):'', chr(61):'', chr(62):'', chr(63):'', chr(64):'', chr(65):'', chr(66):'', chr(67):'', chr(68):'', chr(69):'', chr(70):'', chr(71):'', chr(72):'', chr(73):'1', chr(74):'', chr(75):'', chr(76):'', chr(77):'', chr(78):'', chr(79):'0', chr(80):'', chr(81):'', chr(82):'', chr(83):'', chr(84):'', chr(85):'', chr(86):'', chr(87):'', chr(88):'', chr(89):'', chr(90):'', chr(91):'', chr(92):'', chr(93):'', chr(94):'', chr(95):'', chr(96):'', chr(97):'', chr(98):'', chr(99):'', chr(100):'', chr(101):'', chr(102):'', chr(103):'', chr(104):'', chr(105):'1', chr(106):'', chr(107):'', chr(108):'1', chr(109):'', chr(110):'', chr(111):'0', chr(112):'', chr(113):'', chr(114):'', chr(115):'', chr(116):'', chr(117):'', chr(118):'', chr(119):'', chr(120):'', chr(121):'', chr(122):'', chr(123):'', chr(124):'', chr(125):'', chr(126):'', chr(127):'', chr(128):'', chr(129):'', chr(130):'', chr(131):'', chr(132):'', chr(133):'', chr(134):'', chr(135):'.', chr(137):'', chr(138):'', chr(139):'', chr(140):'0', chr(141):'', chr(142):'', chr(143):'', chr(144):'', chr(145):'', chr(146):'', chr(147):'', chr(148):'', chr(149):'', chr(150):'.', chr(151):'', chr(152):'.', chr(153):'.', chr(154):'', chr(155):'', chr(156):'0', chr(157):'', chr(158):'', chr(159):'', chr(160):'', chr(161):'1', chr(162):'', chr(163):'1', chr(164):'', chr(165):'', chr(166):'1', chr(167):'', chr(168):'', chr(169):'', chr(170):'', chr(171):'', chr(172):'', chr(173):'', chr(174):'', chr(175):'', chr(176):'0', chr(177):'+', chr(178):'2', chr(179):'3', chr(180):'', chr(181):'', chr(182):'', chr(183):'', chr(184):'', chr(185):'1', chr(186):'0', chr(187):'', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'', chr(192):'', chr(193):'', chr(194):'', chr(195):'', chr(196):'', chr(197):'', chr(198):'', chr(199):'', chr(200):'', chr(201):'', chr(202):'', chr(203):'', chr(204):'', chr(205):'1', chr(206):'', chr(207):'1', chr(208):'', chr(209):'', chr(210):'', chr(211):'', chr(212):'0', chr(213):'', chr(214):'0', chr(215):'', chr(216):'0', chr(217):'', chr(218):'', chr(219):'', chr(220):'', chr(221):'', chr(222):'', chr(223):'', chr(224):'', chr(225):'', chr(226):'', chr(227):'', chr(228):'', chr(229):'', chr(230):'', chr(231):'', chr(232):'', chr(233):'', chr(234):'', chr(235):'', chr(236):'', chr(237):'1', chr(238):'', chr(239):'1', chr(240):'0', chr(241):'', chr(242):'', chr(243):'', chr(244):'', chr(245):'0', chr(246):'0', chr(247):'', chr(248):'0', chr(249):'', chr(250):'', chr(251):'', chr(252):'', chr(253):'', chr(254):'', chr(255):''} mappingcharinteger = { chr(1):'', chr(2):'', chr(3):'', chr(4):'', chr(5):'', chr(6):'', chr(7):'', chr(8):'', chr(9):'', chr(10):'', chr(11):'', chr(12):'', chr(13):'', chr(14):'', chr(15):'', chr(16):'', chr(17):'', chr(18):'', chr(19):'', chr(20):'', chr(21):'', chr(22):'', chr(23):'', chr(24):'', chr(25):'', chr(26):'', chr(27):'', chr(28):'', chr(29):'', chr(30):'', chr(31):'', chr(32):'', chr(33):'', chr(34):'', chr(35):'', chr(36):'', chr(37):'', chr(38):'', chr(39):'', chr(40):'', chr(41):'', chr(42):'', chr(43):'', chr(44):'', chr(45):'', chr(46):'', chr(47):'', chr(48):'0', chr(49):'1', chr(50):'2', chr(51):'3', chr(52):'4', chr(53):'5', chr(54):'6', chr(55):'7', chr(56):'8', chr(57):'9', chr(58):'', chr(59):'', chr(60):'', chr(61):'', chr(62):'', chr(63):'', chr(64):'', chr(65):'', chr(66):'', chr(67):'', chr(68):'', chr(69):'', chr(70):'', chr(71):'', chr(72):'', chr(73):'1', chr(74):'', chr(75):'', chr(76):'', chr(77):'', chr(78):'', chr(79):'0', chr(80):'', chr(81):'', chr(82):'', chr(83):'', chr(84):'', chr(85):'', chr(86):'', chr(87):'', chr(88):'', chr(89):'', chr(90):'', chr(91):'', chr(92):'', chr(93):'', chr(94):'', chr(95):'', chr(96):'', chr(97):'', chr(98):'', chr(99):'', chr(100):'', chr(101):'', chr(102):'', chr(103):'', chr(104):'', chr(105):'1', chr(106):'', chr(107):'', chr(108):'1', chr(109):'', chr(110):'', chr(111):'0', chr(112):'', chr(113):'', chr(114):'', chr(115):'', chr(116):'', chr(117):'', chr(118):'', chr(119):'', chr(120):'', chr(121):'', chr(122):'', chr(123):'', chr(124):'', chr(125):'', chr(126):'', chr(127):'', chr(128):'', chr(129):'', chr(130):'', chr(131):'', chr(132):'', chr(133):'', chr(134):'', chr(135):'', chr(137):'', chr(138):'', chr(139):'', chr(140):'0', chr(141):'', chr(142):'', chr(143):'', chr(144):'', chr(145):'', chr(146):'', chr(147):'', chr(148):'', chr(149):'', chr(150):'', chr(151):'', chr(152):'', chr(153):'', chr(154):'', chr(155):'', chr(156):'0', chr(157):'', chr(158):'', chr(159):'', chr(160):'', chr(161):'1', chr(162):'', chr(163):'1', chr(164):'', chr(165):'', chr(166):'1', chr(167):'', chr(168):'', chr(169):'', chr(170):'', chr(171):'', chr(172):'', chr(173):'', chr(174):'', chr(175):'', chr(176):'0', chr(177):'+', chr(178):'2', chr(179):'3', chr(180):'', chr(181):'', chr(182):'', chr(183):'', chr(184):'', chr(185):'1', chr(186):'0', chr(187):'', chr(188):'4', chr(189):'2', chr(190):'4', chr(191):'', chr(192):'', chr(193):'', chr(194):'', chr(195):'', chr(196):'', chr(197):'', chr(198):'', chr(199):'', chr(200):'', chr(201):'', chr(202):'', chr(203):'', chr(204):'', chr(205):'1', chr(206):'', chr(207):'1', chr(208):'', chr(209):'', chr(210):'', chr(211):'', chr(212):'0', chr(213):'', chr(214):'0', chr(215):'', chr(216):'0', chr(217):'', chr(218):'', chr(219):'', chr(220):'', chr(221):'', chr(222):'', chr(223):'', chr(224):'', chr(225):'', chr(226):'', chr(227):'', chr(228):'', chr(229):'', chr(230):'', chr(231):'', chr(232):'', chr(233):'', chr(234):'', chr(235):'', chr(236):'', chr(237):'1', chr(238):'', chr(239):'1', chr(240):'0', chr(241):'', chr(242):'', chr(243):'', chr(244):'', chr(245):'0', chr(246):'0', chr(247):'', chr(248):'0', chr(249):'', chr(250):'', chr(251):'', chr(252):'', chr(253):'', chr(254):'', chr(255):''} def aclone(i): while 1: j=i*2-len(sys.argv[0]) yield(j) return def aaclone(p='123'): a=[]; b=[] for i in range(48,51): a.append(aclone(i+1));b.append(aclone(i+17+32)) if p=='abc': return 'abc' return 'abc',''.join([''.join(b),''.join(a)]) #*** NEW *** mappingcharhtml={} for i in range(256): mappingcharhtml[chr(i)]= "&%d;" % i for entity, char in htmlentitydefs.entitydefs.items(): if mappingcharhtml.has_key(char): mappingcharhtml[char]="&%s;" % entity #*** NEW *** mappingcharhtml2={} for i in mappingcharhtml: if not mappingcharhtml[i][1:-1].isdigit(): mappingcharhtml2[i]=mappingcharhtml[i] # ver 3.232 ; def pu8(ucar): """ conversion d'un caractère cp1252 en format googlemap-utf8-html """ vret='' tmp=str(ucar.decode('cp1252').encode('utf-8','replace')) vret="%"+hex(ord(tmp[0]))[2:].upper()+"%" if len(tmp)>1: vret+=hex(ord(tmp[1]))[2:].upper() return vret # ver 3.232 ; def chpu8(ch): """ conversion d'une chaîne de caractères cp1252 en format googlemap-utf8-html """ vret='' for c in ch: if ord(c)>127: vret+=pu8(c) else: vret+=c return vret # ver 3.233 ; def puhtml(ucar): """ conversion d'un caractère en unicode-html """ return "&#"+str(ord(ucar.decode('utf-8','replace')))+";" """ vret='' tmp=ucar.decode('utf-8','replace') vret="&#"+str(ord(tmp))+";" return vret """ def puhtml127(ucar): """ conversion d'un caractère en unicode-html """ #tmp=ucar.decode('utf-8') if ord(ucar)>127: return "&#"+str(ord(ucar))+";" else: return ucar def chuhtml(ch): """ conversion d'une chaîne de caractères cp1252 en unicode-html """ lt = ''.join([puhtml127(c) for c in ch]) return lt.replace("\r\n","
\r\n") """ vret='' for c in ch: if ord(c)>127: vret+=puhtml(c) else: vret+=c return vret """ def p1252html(ucar): """ conversion d'un caractère en unicode-html """ #tmp=ucar #.decode('utf-8','replace') if ord(ucar)>127: return "&#"+str(ord(ucar))+";" else: return ucar """ vret='' tmp=ucar #.decode('utf-8','replace') vret="&#"+str(ord(tmp))+";" return vret """ # ver 3.233 ; def ch1252html(ch): """ conversion d'une chaîne de caractères cp1252 en unicode-html """ return ''.join([p1252html(c) for c in ch]) """ vret='' for c in ch: if ord(c)>127: vret+=p1252html(c) else: vret+=c return vret """ #*** MODIF 3.6.5 *** def filtrechaine(inp=None, mappingchar=mappingcharmaj): if inp is None: inp=GlobalPARAM[0] return ''.join([mappingchar.get(i, i) for i in u1252(inp)]) #*** NEW 3.6.5 *** def filtrechainep(mappingchar=mappingcharmaj): global chaineretour chaineretour=''.join([mappingchar.get(i, i) for i in u1252(GlobalPARAM[0])]) def convsansaccent(chu, *bof): """ D'une chaine, retourne la même, sans accents, ni diacritiques """ import unicodedata if type(chu) is not unicode: try: chu = unicode(chu,"utf-8",'ignore') except: chu = unicode(repr(chu),"utf-8",'ignore') return unicodedata.normalize('NFD', chu).encode('ascii','ignore') def convsansaccent2(inp=None, mappingchar=mappingcharmaj): """ Ancienne méthode, non Unicode """ global chaineretour if inp is None: inp=GlobalPARAM[0] chaineretour=''.join([mappingchar.get(i, i) for i in u1252(inp)]) return chaineretour #+++ def chdecimal(chaine,espace=1): """Conversion d'un string, en décimal (ord), séparés par le nb de 'espace' """ st='' for c in chaine: st=st+str(ord(c))+' '*espace return st def convhtmlall(inp, mappingchar=mappingcharhtml): """Conversion d'un string, pour utiliser TOUS les caractères HTML @exemple: ab&cdé => &97;&98;&&99;&100;é """ return ''.join([mappingchar.get(i, i) for i in u1252(inp)]) #*** NEW *** def convhtml2(inp, mappingchar=mappingcharhtml2): """Conversion d'un string, pour utiliser les caractères HTML spéciaux @exemple: ab&cdé => ab&cdé """ return ''.join([mappingchar.get(i, i) for i in u1252(inp)]) def convhtml3(inp, mappingchar=mappingcharhtml2): """Conversion d'un string, pour utiliser les caractères HTML spéciaux @exemple: ab&cdé => ab&cdé """ vret=''.join([mappingchar.get(i, i) for i in u1252(inp)]) vret=vret.replace('\r\n','\n') vret=vret.replace('\n','
\n') vret=vret.replace('((','<') vret=vret.replace('))','>') vret=vret.replace(' ','  ') return vret def convhtml4(inp, mappingchar=mappingcharhtml2): """Conversion d'un string, pour utiliser les caractères HTML spéciaux @exemple: ab&cdé => ab&cdé """ vret=''.join([mappingchar.get(i, i) for i in u1252(inp)]) vret=vret.replace('\r\n','\n') vret=vret.replace('\n','
\n') vret=vret.replace(' ','  ') return vret def convhtml(chaine): """Conversion d'un string, pour utiliser les caractères spéciaux HTML @exemple: ab&cdé => ab&cdé """ def remplace(m,get=mappingcharhtml.get): return string.join(map(get,m.group()),"") return re.sub(r'[&<>\"\x80-\xff]+', remplace, chaine) htmlaccent={} htmlaccent[u'à']=u'à' htmlaccent[u'â']=u'â' htmlaccent[u'ä']=u'ä' htmlaccent[u'é']=u'é' htmlaccent[u'è']=u'è' htmlaccent[u'ê']=u'ê' htmlaccent[u'ë']=u'ë' htmlaccent[u'î']=u'î' htmlaccent[u'ï']=u'ï' htmlaccent[u'ô']=u'ô' htmlaccent[u'ö']=u'ö' htmlaccent[u'ù']=u'ù' htmlaccent[u'û']=u'û' htmlaccent[u'ü']=u'ü' htmlaccent[u'ÿ']=u'ÿ' htmlaccent[u'æ']=u'æ' htmlaccent[u'œ']=u'œ' htmlaccent[u'ñ']=u'ñ' htmlaccent[u'ç']=u'ç' htmlaccent[u'€']=u'€' htmlaccent[u'Á']=u'Á' #htmlaccent[unichr(193)]=u'Á' htmlaccent[u'À']=u'À' htmlaccent[u'Â']=u'Â' htmlaccent[u'Ä']=u'Ä' htmlaccent[u'É']=u'É' htmlaccent[u'È']=u'È' htmlaccent[u'Ê']=u'Ê' htmlaccent[u'Ë']=u'Ë' htmlaccent[u'Í']=u'Í' #htmlaccent[unichr(205)]=u'Í' htmlaccent[u'Ì']=u'Ì' htmlaccent[u'Î']=u'Î' htmlaccent[u'Ï']=u'Ï' #htmlaccent[unichr(207)]=u'Ï' htmlaccent[u'Ó']=u'Ó' htmlaccent[u'Ò']=u'Ò' htmlaccent[u'Ô']=u'Ô' htmlaccent[u'Ö']=u'Ö' htmlaccent[u'Ú']=u'Ú' htmlaccent[u'Ù']=u'Ù' htmlaccent[u'Û']=u'Û' htmlaccent[u'Ü']=u'Ü' htmlaccent[u'ÿ']=u'Ÿ' htmlaccent[u'Æ']=u'Æ' htmlaccent[u'Œ']=u'Œ' htmlaccent[u'Ñ']=u'Ñ' htmlaccent[u'Ç']=u'Ç' def convhtmlaccents(chaine): """Conversion d'un string, pour utiliser les caractères spéciaux HTML, pour certains caractères seulement """ """ for c in set(list(chaine)) & set(htmlaccent.keys()): chaine = chaine.replace(c,htmlaccent[c]) return chaine """ for c,r in htmlaccent.iteritems(): chaine = chaine.replace(c,r) #if chaine.find(c)>-1: # chaine = chaine.replace(c,r) return chaine """ for c in htmlaccent: if chaine.find(c)>-1: chaine = chaine.replace(c,htmlaccent[c]) return chaine """ def convhtmlaccents8(chaine): """Conversion d'un string, pour utiliser les caractères spéciaux HTML, pour certains caractères seulement """ #print 4486,type(chaine) s=chaine.decode('cp1252','replace') return convhtmlaccents(s) #*** NEW *** def sinverse(chaine): """Inverse les caractères d'une chaine de caractères @param: chaine de caractères @return: chaine avec les caractères inversés """ return string.join([chaine[i-1] for i in xrange(len(chaine),0,-1)],'') #*** NEW *** def sinverseword(chaine): """Inverse les mots d'une chaine de caractères (séparés par espace, tab, linefeed) @param: chaine de caractères @return: chaine avec les mots inversés, séparés par un espace """ tmplst=chaine.split() tmplst.reverse() return string.join(tmplst,' ') #*** NEW *** def sinverselines(chaine): """Inverse les lignes d'une chaine de caractères @param: chaine de caractères @return: chaine avec les lignes inversées """ tmplst=chaine.splitlines() tmplst.reverse() return string.join(tmplst,'\n') #*** NEW *** def scallbacklines(chaine,callback): """Applique la fonction callback à toutes les lignes d'une chaine @param: chaine de caractères multi-lignes @return: chaine de caractères (multi-lignes) """ tmplst=chaine.splitlines() for i in xrange(len(tmplst)): tmplst[i]=callback(tmplst[i]) return string.join(tmplst,'\r\n') #*** NEW *** def sdel(chaine,debut,fin): """Supprime un ensemble de caractères (de début à fin) d'une chaine. @param: chaine de caractères @return: chaine de caractères, avec caractères supprimés @example: sdel('abcdefg',2,5) --> 'abfg' """ return chaine[:debut]+chaine[fin:] #*** NEW 20.10.05 v2.39b *** def fuschaine(a,b,c=' '): """Fusionne les chaînes a et b, en utilisant le caractère de fond c """ if len(a)>len(b): sret=a[len(b):] else: sret=b[len(a):] return ''.join([l[l[0]==c] for l in zip(a,b)])+sret #*** NEW 28.7.6 v3.219 *** def split_len(seq, length): """Découpe une chaîne en une liste de sous-chaînes de longueur 'count' exemple : 'AABBCCDDE' ==> 'AA','BB','CC','DD','E' Fonctionne aussi avec des listes. exemple : [1,2,3,4,5] ==> ((1, 2), (3, 4), (5,)) """ return [seq[i:i+length] for i in range(0, len(seq), length)] #*** NEW 01.09.07 v3.276 *** def split_m(chaine,*separ): """ Découpe une chaîne d'après un ou plusieurs chaînes-séparatrices exemple : a="aaa|||bbb|||cc#CC|||ddd" split_m(a,'|||','#') => ['aaa', 'bbb', 'cc', 'CC', 'ddd'] """ lret=[chaine] for s in separ: ltemp=[] lret=[ltemp.extend(el.split(s)) for el in lret] lret=ltemp return lret def split_mre(chaine,*separ): """ comme split_m, mais en utilisant les expressions régulières (re). Découpe une chaîne d'après un ou plusieurs chaînes-séparatrices exemple : a="aaa|||bbb|||cc#CC|||ddd" split_mre(a,'|||','#') => ['aaa', 'bbb', 'cc', 'CC', 'ddd'] """ import re pattern = '|'.join(map(re.escape, separ)) return re.split(pattern, chaine) #*** modif v3.3.268 *** def remplacerdansfichiertxt(file, listeremplacement, filout=None): # remplacement dans un fichier texte (et non binary) if os.path.isdir(file): vifi('Directory'+CRLF) else: if filout is None: filout=file data = open(file, "rb").read() if '\0' in data: vifi('Binary'+CRLF) else: newdata=u1252(data) for chaine,remplacement in listeremplacement : newdata = re.sub(u1252(chaine), u1252(remplacement), newdata) if newdata != data: f = open(filout, "wb") f.write(newdata) f.close() vifi(file+' ; '+chaine+' => '+remplacement+' : '+filout+' | OK'+CRLF) #*** cré v3.3.268 *** def remplacerdansfichiertxtgp(file, filout=None): # remplacement dans un fichier texte (et non binary) #msginfo('3249','aaa') #""" if os.path.isdir(file): vifi('Directory'+CRLF) else: if filout is None: filout=file data = open(file, "rb").read() if '\0' in data: vifi('Binary'+CRLF) else: newdata=u1252(data) for chaine,remplacement in zip(GlobalPARAM[::2],GlobalPARAM[1::2]) : newdata = re.sub(u1252(chaine), u1252(remplacement), newdata) if newdata != data: f = open(filout, "wb") f.write(newdata) f.close() vifi(file+' ; '+chaine+' => '+remplacement+' : '+filout+' | OK'+CRLF) def remplacerdansfichierchainetxt(file, listeremplacement): # remplacement dans un fichier texte (et non binary) if os.path.isdir(file): vifi('Directory'+CRLF) else: data = open(file, "rb").read() if '\0' in data: vifi('Binary'+CRLF) else: newdata=data for chaine,remplacement in listeremplacement : newdata = re.sub(chaine, remplacement, newdata) vifi(newdata) chaineretour = newdata #*** NEW *** pour appel direct def remplacerchlst(st, listeremplacement): # dans la chaine (st), on remplace X fois [chaine par remplacement] newdata=st for chaine,remplacement in listeremplacement: newdata = re.sub(chaine, remplacement, newdata) return newdata #*** NEW *** pour appel direct, avec paramètres multiples (X fois chaine,remplacement) def remplacerchxpar(st, *listr): # dans la chaine (st), on remplace X fois [chaine par remplacement] newdata=st for chaine,remplacement in zip(listr[::2],listr[1::2]): newdata = re.sub(chaine, remplacement, newdata) return(newdata) #*** 3.256 ; MODIF si st=None, alors GlobalPARAM[0] def remplacerdanschainetxt(st, listeremplacement): global chaineretour if (st is None) or st=='': st=GlobalPARAM[0] chaineretour = remplacerchlst(st, listeremplacement) def chercherdanschainere(rexpression=None): """Exemple d'utilisation : resul=px.PRun("chercherdanschainere(r'\{HTML.+\/HTML}')",st) for item in resul.split(chr(255)): if len(item): print item.split('\t')[0] # chaine print item.split('\t')[1] # début print item.split('\t')[2] # fin """ global GlobalRGEX,chaineretour,GlobalPARAM if not(rexpression is None): GlobalRGEX=re.compile(rexpression,re.IGNORECASE| re.DOTALL| re.MULTILINE| re.VERBOSE) iter=GlobalRGEX.finditer(GlobalPARAM[0]) chaineretour='' for item in iter: chaineretour=chaineretour+item.group()+SEPARITEMSERIAL+str(item.start()+1)+SEPARITEMSERIAL+str(item.end()-item.start())+SEPARLIGSERIAL #+'\t'+item.groups()+ #*** NEW *** def extraitre(chaine, rexp): """Extrait, d'une chaine, une expression régulière exemple : extraitre(st,r'\{HTML.+\/HTML}') retourne ce qui est compris entre "{HTML." et "/HTML}" @return : une chaine regroupant les correspondances. """ compilre=re.compile(rexp, re.IGNORECASE| re.MULTILINE| re.DOTALL| re.VERBOSE) resul = compilre.findall(chaine) return string.join(resul,'') #*** NEW *** def fifiltre(forig,fdest='',rexp=''): """Copie : - depuis le fichier_ou_chaine forig, dans le fichier fdest, - les seules lignes pour lesquelles rexp (expression régulière) est vraie. Si forig a une longueur inférieure à 100 caractères, la fonction tente de lire un fichier. Si cela échoue, ou si la taille est plus grande, forig est traité comme une chaine. exemple : fifiltre('reess.txt','reess2.txt',r'(t..?t)') extrait les lignes qui contiennent 't', un ou deux caractères, et 't' """ global chaineretour if len(forig)<100: if os.path.isfile(forig): fm = open(forig,'rb') chaine = fm.read() fm.close() else: chaine=forig else: chaine=forig compilre=re.compile(rexp, re.IGNORECASE) f=cStringIO.StringIO() nb=0 if chaine.find('\r\n')>-1: L=chaine.split('\r\n') else: L=chaine.split('\n') for lig in L: if compilre.search(lig): nb+=1 if nb==1: f.write(lig) else: f.write('\r\n'+lig) chaineretour=f.getvalue() f.close() if fdest!='': f=open(fdest,'w') f.write(chaineretour) f.close() return chaineretour #*** NEW 3.211 *** def modifilestr(fil, position, chaine): """ écrit une chaîne dans un fichier, à une position donnée @param: fil: nom du fichier position: index du premier caractère où écrire (commence à 0) chaine: string à écrire """ f = open(fil, 'r+') f.seek(position) f.write(chaine) f.close() #*** NEW 3.211 *** def lintstr(*lint): """ Retourne un string, composé par une liste de codes ascii """ st='' for i in lint: st=st+chr(i) return st #*** NEW 3.211 *** def modifilesint(fil, position, *lint): """ écrit une chaîne dans un fichier, à une position donnée @param: fil: nom du fichier position: index du premier caractère où écrire (commence à 0) *lint: liste d'entiers des codes ascii du string à écrire """ modifilestr(fil, position, lintstr(*lint)) #*** NEW *** def fcalc(chaine=None): """Calcule une chaine de caractères. Cette chaine est, soit passée en paramètre, soit par GlobalPARAM[0] """ global chaineretour,Global_fcalcRE if chaine is None: chaine=GlobalPARAM[0] if Global_fcalcRE is None: Global_fcalcRE=re.compile('([\d.]+)', re.IGNORECASE| re.MULTILINE| re.DOTALL| re.VERBOSE) resul = Global_fcalcRE.findall(chaine) L=Global_fcalcRE.split(chaine) for index in range(len(L)): item=L[index] if item in resul: if item.find('.')<0: L[index]=item+'.' chaineretour=eval(''.join(L)) return chaineretour def deserialize(obj, smode='COMPRESS'): if smode=='COMPRESS': return cPickle.loads(zlib.decompress(obj)) else: return cPickle.loads(obj) def serialize(obj, smode='COMPRESS'): if smode=='COMPRESS': return zlib.compress(cPickle.dumps(obj,1)) else: return cPickle.dumps(obj,1) def convcodec(fparam, fdest, ccodec='utf-8'): if len(fparam)<120: fm = open(fparam,'rb') chaine = fm.read() fm.close() else: chaine=fparam fhandle=codecs.open(fdest,'w', ccodec, 'replace') fhandle.write(chaine) fhandle.close() def iconvcodec(chaine,codeorig='cp1252',codedest='UTF-8'): global chaineretour import codecs import iconv_codec a=unicode(chaine.decode(codeorig)) return(a.encode(codedest,'replace')) def lintuni(*cardec): #génère une chaîne unicode, d'après un ensemble d'entiers (en paramètres) uret=unicode('') for cu in cardec: uret=uret+unichr(cu) return uret def sintuni(lcardec): #génère une chaîne unicode, d'après une liste d'entiers-strings (en paramètres) uret=unicode('') for cu in lcardec: if cu!='': uret=uret+unichr(int(cu)) return uret def urtf(lcardec): #génère une chaîne unicode, d'après une liste de strings-RTF (en paramètres) uret=unicode('') for cu in lcardec: if cu!='': #print int(cu[2:-1]), i=int(cu[2:-1]) if i>0: uret=uret+unichr(i) else: uret=uret+unichr(65536+i) return uret def htmluni(chaine): #retrouve une liste d'entiers-strings, d'après un fichier_ou_string HTML "simple" if os.path.isfile(chaine): f=open(chaine,"r") st=f.read() else: st=chaine st = re.sub('(<.*>)','',st) st = re.sub('( )','',st) st = re.sub('(\.)','',st) st = re.sub('(\r\n)','',st) st = re.sub('(\n)','',st) st = re.sub('(\r)','',st) st = re.sub('(&#)','',st) lst = string.split(st,';') return sintuni(lst) def unihtml(suni, fichier=None, tete=True, pied=True): #génère un string_ou_fichier HTML contenant un txt unicode ch='' if tete==True: ch=ch+"\r\n" n=0 for cu in suni: ch=ch+'&#'+str(ord(cu))+';' n=n+1 if n==10: ch=ch+'\r\n' n=0 if pied==True: ch=ch+'\r\n' if fichier: f=open(fichier,'w') f.write(ch) f.close() return ch def unipdxhtml(suni, fichier=None): # acf ch=""" \r\n""" n=0 for cu in suni: n=n+1 ch=ch+'&#'+str(ord(cu))+';' ch=ch+'\r\n' ch+='''
\r\n''' n=0 for cu in suni: n=n+1 ch=ch+'&#'+str(ord(cu))+';' ch=ch+'''\r\n ''' if fichier: f=open(fichier,'w') f.write(ch) f.close() return ch def unitk(suni): #visu un txt unicode dans une boîte d'alerte TK import Tkinter import tkFont root = Tkinter.Tk() myFont = tkFont.Font(size=24) w = Tkinter.Label(root, text=suni, font=myFont) w.pack() root.mainloop() #*** Modif *** ajout typ def uniw32dia(suni, titre=u'Texte unicode', typ=0): #visu un txt unicode dans une boîte d'alerte import ctypes MessageBoxW = ctypes.windll.user32.MessageBoxW MessageBoxW.argtypes = ctypes.c_int, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_int """OKONLY = 0 OKCANCEL = 1 ABORTRETRYIGNORE = 2 YESNOCANCEL = 3 YESNO = 4 CRITICAL = 16 QUESTION = 32 EXCLAMATION = 48 INFORMATION = 64 """ return MessageBoxW(0, suni, titre, typ) #en retour : 6 = OUI 7 = NON #*** NEW *** ajout typ def uniw32diaA(suni, titre=u'Texte unicode', typ=0): #visu un txt unicode dans une boîte d'alerte import ctypes MessageBoxA = ctypes.windll.user32.MessageBoxA MessageBoxA.argtypes = ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int """OKONLY = 0 OKCANCEL = 1 ABORTRETRYIGNORE = 2 YESNOCANCEL = 3 YESNO = 4 CRITICAL = 16 QUESTION = 32 EXCLAMATION = 48 INFORMATION = 64 """ return MessageBoxA(0, suni, titre, typ) #en retour : 6 = OUI 7 = NON def messageboxduree(titre='Titre',texte='Message', duree=3): import win32gui,win32con,win32com.client,threading,time,types bouton=['USER'] if duree>0: shell = win32com.client.Dispatch("WScript.Shell") def echap(): time.sleep(duree) if win32gui.FindWindowEx(0,0,0,titre) > 0: shell.SendKeys("{ESCAPE}") bouton[0]="FINTHREAD" tach=threading.Thread(target=echap,name="2secondes") tach.setDaemon(True) tach.start() if isinstance(texte, basestring): txt=texte.decode('utf-8','ignore').encode('cp1252','ignore') else: txt=str(texte) #tretour = win32ui.MessageBox(txt, titre, win32con.MB_OK) tretour = win32api.MessageBox(win32con.MB_OK, txt, titre) return bouton[0] def automessage(texte=u'Prêt'): if not os.path.isfile(GlobalPonxDir+'\\automessage.hta'): open(GlobalPonxDir+'\\automessage.hta','wb').write(r''' ''') open('automessage.txt','wb').write(' ') os.startfile(ponxdir()+'\\automessage.hta') pglobal.mcycle=[] for i in range(25): pglobal.mcycle.append(' ') def traite(txt): if txt=='END': open('automessage.txt','w+').write('END') pglobal.mcycle=[] for i in range(25): pglobal.mcycle.append(' ') else: try: del(pglobal.mcycle[0]) except: pass """ pglobal.mcycle=[] mcycle=pglobal.mcycle for i in range(25): mcycle.append(' ') """ try: txt2=txt.encode('cp1252','replace') except: try: txt2=str(txt) except: txt2=txt pglobal.mcycle.append(txt2) texte='\r'.join(pglobal.mcycle) open('automessage.txt','w+').write(texte) traite(texte) traite(' ') return traite #*** NEW *** def msginfo(titre='Titre',txt='Texte'): if not isinstance(titre, (basestring,unicode)): try: titre=str(titre) except: pass if not isinstance(txt, (basestring,unicode)): try: txt=str(txt) except: pass try: uniw32dia(u1252(txt.decode('utf-8')),u1252(titre.decode('utf-8'))) except: uniw32dia(u1252(txt),u1252(titre)) """ try: win32api.MessageBox(1,u1252(txt.decode('utf-8')),u1252(titre.decode('utf-8'))) except: win32api.MessageBox(1,u1252(txt),u1252(titre)) """ #*** NEW *** ; version 'ANSI' ? def msginfoA(titre='Titre',txt='Texte'): uniw32diaA(txt,titre) #*** NEW *** ; version 'ANSI' ? def tmessage(txt='Texte',duree=3000): contenu="""

TTTT
""" texte=u1252(txt) texte=texte.replace("\r\n","
") texte=texte.replace("\n","
") contenu=contenu.replace('3333',str(duree)) contenu=contenu.replace('TTTT',texte) f=open("C:\\temp.hta","w") f.write(contenu) f.close() if os.path.isfile("C:\\windows\\system32\\mshta.exe"): os.spawnv(os.P_NOWAIT,"C:\\windows\\system32\\MSHTA.EXE",["C:\\windows\\system32\\MSHTA.EXE","c:\\temp.hta"]) if os.path.isfile("C:\\winnt\\system32\\mshta.exe"): os.spawnv(os.P_NOWAIT,"C:\\winnt\\system32\\MSHTA.EXE",["C:\\winnt\\system32\\MSHTA.EXE","c:\\temp.hta"]) time.sleep(0.5) #os.remove('C:\\temp.hta) def rtftableau(nblig=3,couleur=(192,192,192),*cols): """ Prépare un tableau en RTF. Couleur en RVB Colonnes en cm Le résultat peut être copié dans le presse-papier. Exemples : data = rtftableau((0,192,255),10) ponx.clipboard_set('Rich Text Format',data) data = rtftableau((0,192,255),2,8,3) ponx.clipboard_set('Rich Text Format',data) """ if cols==() or cols==[]: cols=(2,8,2) if cols is None: cols=(2,8,2) scouleur="{\\colortbl ;" scouleur += "\\red"+str(couleur[0]) scouleur += "\\green"+str(couleur[1]) scouleur += "\\blue"+str(couleur[2]) scouleur += ";}" data="""{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1036{\\fonttbl{\\f0\\fnil\\fcharset0 Calibri;}{\\f1\\fnil Calibri;}} """+scouleur+""" {\\*\\generator Msftedit 5.41.21.2509;}\\viewkind4\\uc1 .LIGNE. \\pard\\sa200\\sl276\\slmult1\\lang12\\f0\\par }""" lig0=""" \\trowd\\trgaph70\\trleft-108 \\trbrdrl\\brdrs\\brdrw10 \\trbrdrt\\brdrs\\brdrw10 \\trbrdrr\\brdrs\\brdrw10 \\trbrdrb\\brdrs\\brdrw10 \\trpaddl70\\trpaddr70\\trpaddfl3\\trpaddfr3 """ bof="""\\cellx1843\\cellx6096\\cellx8080""" lig1=""" \\pard\\intbl\\cell\\cell\\cell\\row """ ligs="" for i in range(nblig): c="" cumul=0 for j in cols: cumul+=j cellul="""\\clbrdrl\\brdrw10\\brdrs\\brdrcf1 \\clbrdrt\\brdrw10\\brdrs\\brdrcf1 \\clbrdrr\\brdrw10\\brdrs\\brdrcf1 \\clbrdrb\\brdrw10\\brdrs\\brdrcf1 """ c += cellul+"\\cellx"+str(int((cumul-0.16)*1000.0/1.76)) ligs += lig0+c+lig1 data = data.replace(".LIGNE.",ligs) return data+'\0' #*** NEW 3.204 *** def add_method_to_objects_class(object, name=None): def prep(nomf): st="""def """+nomf+"""(self, *par): sret=self.run('"""+nomf+"""',*par) return sret method="""+nomf+""" """ return st if name is None: name = method.func_name #print"zzzzzzzzzzzz",name sss=prep(name) #print "sss",sss exec(sss,globals(),globals()) #print "method",method class newclass(object.__class__): pass setattr(newclass, name, method) object.__class__ = newclass class ax(object): import win32com.client oscr=None lang=None dfunc={} def __init__(self, lang='vbscript'): self.oscr=win32com.client.Dispatch('ScriptControl') self.oscr.Language=lang self.lang=lang def add(self, src=None): if src is None: self.oscr.AddCode(GlobalPARAM[0]) else: #self.oscr.AddCode(src) self.oscr.AddCode(src.decode('utf-8','replace').encode('cp1252','replace')) def addfunc(self, src, name): self.add(src) self.dfunc[name]=src add_method_to_objects_class(self, name) def eval(self, src=None): if src is None: return self.oscr.Eval() else: return self.oscr.Eval(src) def srun(self): self.oscr.Run() def run(self, src=None, *par): if src is None: return self.oscr.Run() else: return self.oscr.Run(src,*par) def language(self): return self.lang def oscrattr(self,attribut): vret=eval('self.oscr.'+attribut) return vret def test(self): self.oscr.Run(oaddtext,'AAAAA') def test2(self, a, b): return a+b #*** NEW 03.06.05 *** def wscriptBridgeOpen(lang='vbscript'): global GlobalWscript import win32com.client GlobalWscript=win32com.client.Dispatch('ScriptControl') GlobalWscript.Language=lang #*** NEW 03.06.05 *** def wscriptBridgeAdd(src=None): if src is None: return GlobalWscript.AddCode(GlobalPARAM[0]) else: return GlobalWscript.AddCode(src) #*** NEW 03.06.05 *** def wscriptBridgeEval(src=None): global chaineretour if src is None: chaineretour=GlobalWscript.Eval(u1252(GlobalPARAM[0])) else: chaineretour=GlobalWscript.Eval(src) #msginfo(src,chaineretour) return chaineretour #*** NEW 03.06.05 *** def wscriptBridgeRun(src=None, *par): global chaineretour,GlobalPARAM if src is None: #for i in range(len(GlobalPARAM)): # GlobalPARAM[i]=u1252(GlobalPARAM[i]) #msginfo(src,str(GlobalPARAM)) chaineretour=GlobalWscript.Run(*GlobalPARAM) else: chaineretour=GlobalWscript.Run(u1252(src),*par) GlobalPARAM=chaineretour #msginfo(src,str(GlobalPARAM)) return chaineretour #*** NEW 2.39d ; 25.10.05 *** def wscriptBridgeRunA(func=None): """ Appel de Run, avec la fonction func, et les paramètres dans un tableau (GlobalPARAM) Le retour peut être une liste, ou une valeur. """ global chaineretour,GlobalPARAM #msginfo(func,str(GlobalPARAM)) GlobalPARAM=GlobalWscript.Run(u1252(func),GlobalPARAM) #msginfo(src,chaineretour) return GlobalPARAM #*** NEW 3.6.5 *** def winobjX(titrewin=None,idcontrol=None): global chaineretour chaineretour=None if (not (titrewin is None)) and (not(idcontrol is None)): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.ControlGetPosX(titrewin,'',idcontrol) del auto return chaineretour #*** NEW 3.6.5 *** def winobjY(titrewin=None,idcontrol=None): global chaineretour chaineretour=None if (not(titrewin is None)) and (not(idcontrol is None)): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.ControlGetPosY(titrewin,'',idcontrol) del auto return chaineretour #*** NEW 3.6.5 *** def winobjW(titrewin=None,idcontrol=None): global chaineretour chaineretour=None if (not(titrewin is None)) and (not(idcontrol is None)): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.ControlGetPosWidth(titrewin,'',idcontrol) del auto return chaineretour #*** NEW 3.6.5 *** def winobjH(titrewin=None,idcontrol=None): global chaineretour chaineretour=None if (not(titrewin is None)) and (not(idcontrol is None)): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.ControlGetPosHeight(titrewin,'',idcontrol) del auto return chaineretour def winobjgettext(titrewin=None,idcontrol=None): """Lit le contenu (texte) d'un contrôle d'une fenêtre Exemple winobjgettext('Calculat','[CLASS:Edit; INSTANCE:1]') """ global chaineretour chaineretour=None if (not(titrewin is None)) and (not(idcontrol is None)): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.ControlGetText(titrewin,'',idcontrol) del auto return chaineretour def winobjsettext(titrewin=None,idcontrol=None,txt=''): """écrit le contenu (texte) d'un contrôle d'une fenêtre Exemple winobjsettext('Calculat','[CLASS:Edit; INSTANCE:1]','112233.44') """ global chaineretour chaineretour=None if (not(titrewin is None)) and (not(idcontrol is None)): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.ControlSetText(titrewin,'',idcontrol,txt) del auto return chaineretour #*** NEW 3.6.5 *** def winX(titrewin=None): global chaineretour chaineretour=None if not(titrewin is None): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.WinGetPosX(titrewin) del auto return chaineretour #*** NEW 3.6.5 *** def winY(titrewin=None): global chaineretour chaineretour=None if not(titrewin is None): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.WinGetPosY(titrewin) del auto return chaineretour #*** NEW 3.6.5 *** def winW(titrewin=None): global chaineretour chaineretour=None if not(titrewin is None): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.WinGetPosWidth(titrewin) del auto return chaineretour #*** NEW 3.6.5 *** def winH(titrewin=None): global chaineretour chaineretour=None if not(titrewin is None): auto=win32com.client.Dispatch('AutoItX3.Control') chaineretour=auto.WinGetPosHeight(titrewin) del auto return chaineretour #*** NEW 3.17 *** def get_DLL_version_number(filename=None): from win32api import GetFileVersionInfo, LOWORD, HIWORD if filename is None: filename=GlobalPARAM[0] info = GetFileVersionInfo(filename, "\\") ms = info['FileVersionMS'] ls = info['FileVersionLS'] return str(HIWORD(ms))+'.'+str(LOWORD(ms))+'.'+str(HIWORD(ls))+'.'+str(LOWORD(ls)) #*** new 01.09.07 ; v3.276 *** def win_findbytitre(wintitre="INC-Message"): """ Cherche une fenêtre par son titre, et retourne son handle """ h_window = win32gui.FindWindowEx(0,0,0,wintitre) #print h_window,hex(h_window) if h_window>0: #print win32gui.GetWindowText(h_window) pass return h_window #*** new 01.09.07 ; v3.276 *** def win_wm_copydata(win_h_window=None,txt='AZERTY', timeout=1000): """ Envoie une chaîne à une fenêtre (repérée par son handle), par le système de messages de windows (WM_COPYDATA). Bien adapté à incmessage.exe, mais peut aussi servir à communiquer avec une fenêtre AutoIt """ import struct,array data = array.array( 'c', txt+chr(0)) data_ad, data_len = data.buffer_info() datastruct = array.array('c', struct.pack("IIP", data_len, data_len, data_ad)) #and make a pointer to it struct_message = datastruct.buffer_info()[0] #ancienne ligne, sans timeout (= infini) #win32api.SendMessage(win_h_window, win32con.WM_COPYDATA, 0, struct_message) win32gui.SendMessageTimeout(win_h_window, win32con.WM_COPYDATA, 0, struct_message, win32con.SMTO_NORMAL, timeout) def win_wm_copydata_titre_h(hwin, par): """ utilisé par win_wm_copydata_titre """ contient = par[0] data = par[1] st=win32gui.GetWindowText(hwin) if st.find(contient)>-1: #print st #msginfo(5589,contient) if hwin!=0: try: win_wm_copydata(hwin,data) except: pass def win_wm_copydata_titre(rtitre,data): """ Envoie un message_windows WM_COPYDATA à toute fenêtre dont le titre contient rtitre, utiliser des titres en Unicode """ win32gui.EnumWindows(win_wm_copydata_titre_h,(rtitre,data)) #*** new 01.09.07 ; v3.276 *** def win_premierplan_h(hwin, r): """ Met au premier plan une fenêtre (repérée par son handle), si son titre contient les deux chaînes-repères r[0] et r[1] (qui peuvent être vide) Appelé par win_premierplan """ st=win32gui.GetWindowText(hwin) if st.find(r[0])>-1 and st.find(r[1])>-1: #print st if hwin!=0: try: win32gui.SetForegroundWindow(hwin) except: pass #*** new 01.09.07 ; v3.276 *** def win_premierplan(r1,r2): """ Met au premier plan toute fenêtre dont le titre contient les deux chaînes-repères r1 et r2 utiliser des chaines-repères en Unicode """ win32gui.EnumWindows(win_premierplan_h,(r1,r2)) #*** new 02.09.07 ; v3.277 *** def win_hide_h(h): win32gui.ShowWindow(h, win32con.SW_HIDE) #*** new 02.09.07 ; v3.277 *** def win_show_h(h): win32gui.ShowWindow(h, win32con.SW_SHOWNORMAL) #*** new 02.09.07 ; v3.277 *** def win_move_h(hwin,x,y,w=None,h=None): if w: win32gui.MoveWindow(hwin, x, y, w, h, 1) else: xx,yy,ll,hh=win_getwinrect(hwin) win32gui.MoveWindow(hwin, x, y, ll,hh, 1) #*** new 02.09.07 ; v3.277 *** def win_setactive(h): win32gui.SetActiveWindow(h) def win_destroy(h): win32gui.DestroyWindow(h) #*** new 02.09.07 ; v3.277 *** def win_setfocus(h): win32gui.ShowWindow(h, win32con.WM_SETFOCUS) #*** new 02.09.07 ; v3.277 *** def win_gettitle(h): return win32gui.GetWindowText(h) #*** new 02.09.07 ; v3.277 *** def win_getwinrectstr(h): taille = win32gui.GetWindowRect(h) return str(taille) #*** new 02.09.07 ; v3.277 *** def win_getclientrectstr(h): taille = win32gui.GetClientRect(h) return str(taille) #*** new 02.09.07 ; v3.277 *** def w32_mousemove(x,y): win32api.SetCursorPos((x,y)) #*** new 02.09.07 ; v3.277 *** def w32_mouseclick(mousebt): bouton=str(mousebt).upper() if bouton.startswith('LEF'): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,100,100,0) time.sleep(0.01) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,100,100,0) elif bouton.startswith('RIG'): win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,100,100,0) time.sleep(0.01) win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,100,100,0) #*** new 02.09.07 ; v3.277 *** def w32_sendkeys(param): shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys(u1252(param)) """ {~} {!} {^} {+} {ALT} {BACKSPACE} {CLEAR} {DELETE} {DOWN} {END} {ENTER} {ESCAPE} {F1} à {F16} {PGDN} {SPACE} {TAB} SHIFT prefix with + CTRL prefix with ^ ALT prefix with % """ #*** new 02.09.07 ; v3.277 *** def win_getwinrect(h): x,y,l,h = win32gui.GetWindowRect(h) return x,y,l,h #*** new 02.09.07 ; v3.277 *** def win_getclientrect(h): x,y,l,h = win32gui.GetClientRect(h) return x,y,l,h def explorerinvoke(chemin,fichier="",verbe=""): """ invoque une ligne du menu contextuel de l'explorateur. paramètres: - chemin (peut être un disque) - fichier (facultatif, si "", alors on traite le dossier) - verbe, la ligne du menu à invoquer Notes: Le script ne doit pas être fermé tant que la fonction appelée n'est pas terminée. Exemples: explorerinvoke("L:","",u"Propriétés") explorerinvoke("L:\\","choixdir.py",u"Textpad") explorerinvoke("L:\\","choixdir.py",u"Créer un raccourci") (cet exemple travaille de manière invisible) """ if verbe=="": return objShell = win32com.client.Dispatch('Shell.Application') wshell=win32com.client.Dispatch("WScript.Shell") objFolder = objShell.Namespace(chemin) if fichier!="": objFolderItem = objFolder.ParseName(fichier) else: objFolderItem = objFolder.Self colVerbs = objFolderItem.Verbs() ordre=None verbe=verbe.upper() num=-1 for objVerb in colVerbs: num+=1 if objVerb.Name!="": st=objVerb.Name st=st.replace('&','') st=st.upper() #print num,' \t ',st,' ',verbe, if st==verbe: ordre=objVerb #objVerb.DoIt() colVerbs.Item(num).DoIt() n=wshell.Popup(verbe,1,u"Commande envoyée",0) break #***modif: 3.258 *** def pbridgedir(): """Cherche ,le répertoire de PBridge.htm (répertoire courant, puis ponxdir()+'\\PBridge') """ if os.path.isfile(os.getcwd()+'\\Pbridge.htm'): return os.getcwd() else: return ponxdir()+'\\PBridge' #***new: 3.257 *** #***modif: 3.258 *** def connectpbridge(compteur=2): """Se connecte à PBridge ; si échec tente (une fois) de lancer 0PBridge.hta (du répertoire de PBridge) """ while compteur>0: clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' #print "Dispatch", hie=win32com.client.Dispatch(clsid) #print "Ok." for i in range(hie.Count): #print "connecte une instance", instance=hie[i] #print "Ok." try: if instance.Document.parentWindow.name=='PBridge': compteur=0 wpx=instance.Document.parentWindow px=wpx.ponx; pd=wpx.ponxd; htawin=wpx.htawin return px,pd,htawin,wpx except: pass def launchpbridge(): os.startfile(pbridgedir()+'\\0Pbridge.hta') time.sleep(8) #print 'lancé.' compteur-=1 launchpbridge() if compteur>0: return connectpbridge(compteur) else: return None,None,None,None def connectpbridged(compteur=2): return list(connectpbridge(compteur)) #***new: 3.286 *** def testpbridge(): """ teste PBridge, en tentant de le (re)-lancer s'il n'est pas trouvé au 1er coup """ pbpx,pbpd,pbhtawin,pbwpx=connectpbridge() if pbpx is None: return False else: return True #***new: 3.307 *** def connect1pbridge(): """ tente de se connecter à PBridge, une seule fois. Si réussite, retourne htawin En cas d'échec, retourne None exemple d'utilisation : import win32com.client pd = win32com.client.Dispatch('Ponxd.Mci') htawin=pd.connect1pbridge() if not htawin: print 'impossible de joindre PBridge/Ponx' else: print "Close",htawin.name htawin.closepbridge('aa') """ # Attention : # wpx n'est pas "printable" ; toujours utiliser une propriété, comme wpx.name # idem avec htawin clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' hie=win32com.client.Dispatch(clsid) for i in range(hie.Count): instance=hie[i] try: if instance.Document.parentWindow.name=='PBridge': wpx=instance.Document.parentWindow px=wpx.ponx; pd=wpx.ponxd; htawin=wpx.htawin return wpx #px,pd,htawin,wpx except: pass return None #None,None,None,None def cachepbridge(fenetre=''): if fenetre=='' or fenetre.upper()=='ALL' or fenetre.upper()=='PBRIDGE': for instance in win32com.client.Dispatch('{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'): if instance.LocationURL.endswith('PBridge.htm'): instance.Visible=False if fenetre=='' or fenetre.upper()=='ALL' or fenetre.upper()=='0PBRIDGE': h0 = win32gui.FindWindowEx(0,0,0,'0PBridge') win32gui.ShowWindow( h0, win32con.SW_HIDE) def montrepbridge(fenetre=''): if fenetre=='' or fenetre.upper()=='ALL' or fenetre.upper()=='PBRIDGE': for instance in win32com.client.Dispatch('{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'): if instance.LocationURL.endswith('PBridge.htm'): instance.Visible=True if fenetre=='' or fenetre.upper()=='ALL' or fenetre.upper()=='0PBRIDGE': h0 = win32gui.FindWindowEx(0,0,0,'0PBridge') win32gui.ShowWindow( h0, win32con.SW_SHOW) #***new: 3.263 *** def testerelancepbridgetps(tps=True, pbridge=True): import _winreg,sys,os,os.path,re,win32com.client try: name, ponxdir, typ = _winreg.EnumValue(_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Classes\CLSID\{EC501258-201C-449C-BE20-837A316EA382}\PythonCOMPath'), 0) except: ponxdir=os.getcwd() sdir1=ponxdir sdir2=ponxdir+"\\PBridge" wmihandle = win32com.client.GetObject('winmgmts:') if tps: re_obj = re.compile(r'tps.py', re.IGNORECASE| re.MULTILINE) wmihandle = win32com.client.GetObject('winmgmts:') process_list = wmihandle.ExecQuery('Select * from Win32_Process where name="pythonw.exe"') flag=True #print process_list[0].GetObjectText_() for p in process_list: if re_obj.search(p.CommandLine): flag=False if flag: os.chdir(sdir1) #print os.getcwd() os.system('start "" tps.pyw tps.cfg') if pbridge: re_obj = re.compile(r'0PBridge.hta', re.IGNORECASE| re.MULTILINE) wmihandle = win32com.client.GetObject('winmgmts:') process_list = wmihandle.ExecQuery('Select * from Win32_Process where name="mshta.exe"') flag=True #print process_list[0].GetObjectText_() for p in process_list: if re_obj.search(p.CommandLine): flag=False if flag: os.chdir(sdir2) #print os.getcwd() os.system('start "" 0PBridge.hta') #***new: 3.262 *** # ancienne version, qui ne marche pas sous windows-2000 (à cause TaskList.exe) def testerelancepbridgetpsOLD(tps=True, pbridge=True): import _winreg,sys,os,os.path try: name, ponxdir, typ = _winreg.EnumValue(_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Classes\CLSID\{EC501258-201C-449C-BE20-837A316EA382}\PythonCOMPath'), 0) except: ponxdir=os.getcwd() sdir1="CD /D"+ponxdir sdir2="CD /D"+ponxdir+"\\PBridge" bat1='' bat2='' bat3='' bat4='' bat5='' bat1='''@echo off ''' if tps: bat2='''for /F "usebackq" %%a in (`tasklist ^|find "pythonw"`) DO goto :SUITE for /F "usebackq" %%a in (`tasklist ^|find "python"`) DO goto :SUITE '''+sdir1+''' start "" tps.pyw tps.cfg ''' bat3=''' :SUITE ''' if pbridge: bat4='''for /F "usebackq" %%a in (`tasklist ^|find "mshta"`) DO goto :FIN '''+sdir2+''' start "" 0PBridge.hta ''' bat5=''' :FIN exit ''' bat=bat1+bat2+bat3+bat4+bat5 open('C:\\temp.bat','w').write(bat) os.system('start "" C:\\temp.bat') #*** NEW *** ; ne marche qu'à l'installation du serveur COM #atexit.register(msginfo,"PONX","Va se terminer.") # modif 3.237 def ftpconnect(): # se connecte au serveur FTP global host,port,login,pwd,path,pathlocal,connftp connftp = ftplib.FTP() connftp.connect(host, port) connftp.getwelcome( ) connftp.login(login, pwd) connftp.cwd(path) vret=_("Le serveur répond : ")+str(connftp.getwelcome()) vifi(vret) return vret # new 3.237 def ftpconnectpar(host1,port1,login1,pwd1,path1,pathlocal1='C:\\',*flist1): # se connecte au serveur FTP global host,port,login,pwd,path,pathlocal,connftp,flist host=host1 port=port1 login=login1 pwd=pwd1 path=path1 pathlocal=pathlocal1 flist=flist1 return ftpconnect() def ftpclose(): # ferme la connexion FTP global connftp vifi(connftp.quit()) #vifi(connftp.close()) def ftpretrlines(cmd='LIST', callback=None): global connftp if callback is None: buf=connftp.retrlines(cmd) else: buf=connftp.retrlines(cmd, callback) vifi(buf) return str(buf) # new 3.327 def ftpdirs(): global connftp,chaineretour,GlobalPARAMliste #chaineretour=str(connftp.pwd()) GlobalPARAMliste[:]=connftp.nlst() retourljoin() return chaineretour # new 3.327 def ftpdirl(): global connftp return connftp.nlst() # new 3.327 def ftpdelete(*argu): global connftp,chaineretour chaineretour="" for f in argu: chaineretour+=str(f)+" "+connftp.delete(f)+"\r\n" #msginfo("f",f) return chaineretour #*** 16.08.05 ; v 2.38 ; modif, pour gérer flist=[] *** def ftpupload(): # envoi une liste de fichiers vers un serveur FTP global host,port,login,pwd,path,pathlocal,flist,connftp if flist==[]: flist=os.listdir(pathlocal) #msginfo(pathlocal,str(flist)) import pywig pmessage=pywig.incmessage() for num,fi in enumerate(flist): #print "fi",pathlocal+'\\'+fi, #tmessage(txt=fi,duree=2000) try: pmessage([str(num),'',fi]) except: try: pmessage([str(num),'',fi.encode('cp1252','replace')]) except: pmessage([str(num),'',str(num)]) #envoiautoitautomessage(u"MESSAGE|||"+fi) try: f = open(pathlocal+'\\'+fi,"rb") except: #tmessage(txt='''ERREUR\r\nsur fichier'''+pathlocal+'\\'+fi,duree=5000) pmessage([str(num),'','ERREUR sur fichier'+pathlocal+'\\'+fi]) ##stemp=u'''ERREUR\r\nsur fichier'''+pathlocal+'\\'+fi ##envoiautoitautomessage(u"MESSAGE|||"+stemp.decode('utf-8','replace')) time.sleep(5) continue #print '->', try: connftp.storbinary("STOR " + fi, f, 8192) #print 'Ok', try: vifi(_("Envoi (upload) du fichier ")+fi+" : Ok.") except: try: vifi(_("Envoi (upload) du fichier ")+fi+" : Ok.") except: vifi(_("Envoi (upload) du fichier ")+fi.encode('cp1252','replace')+" : Ok.") pass except: #tmessage(txt='''ERREUR ftp storbinary''',duree=5000) pmessage([str(num),'','ERREUR ftp storbinary']) ##stemp=u'''ERREUR ftp storbinary''' ##envoiautoitautomessage(u"MESSAGE|||"+stemp.decode('utf-8','replace')) #print 'Erreur envoi sur '+pathlocal+'\\'+fi, try: vifi(_("Erreur d'envoi, fichier ")+fi+" : Error.") except: vifi(_("Erreur d'envoi, fichier ")+fi.encode('cp1252','replace')+" : Error.") #print '.' try: f.close() except: pass pmessage() del(pmessage) def ftpdownload(): # lit (recupère) une liste de fichiers depuis le serveur FTP global host,port,login,pwd,path,pathlocal,flist for file in flist: vifi(_("Récupération (download) du fichier ")+file+" : Ok.") f = open(pathlocal+file,"wb") connftp.retrbinary("RETR " + file, f.write, 8192) #*** new 3.20 def ftpsyncup(phost, plogin, ppassw, prep, localdrive, localpath, localrep): global host,port,login,pwd,path,pathlocal,flist,connftp,GlobalPARAMliste host=phost port=21 login=plogin pwd=ppassw path=prep resul='connexion : ' try: resul=ftpconnect() except: resul+='échec.' #tmessage(txt=resul,duree=3000) ##autoitautomessageload() ##envoiautoitautomessage("MESSAGE|||"+resul) #vifi(resul) GlobalPARAMliste=[] ftpretrlines('LIST',ftpstodir) #print GlobalPARAMliste dicftp={} for i in GlobalPARAMliste: #print ponx.u1252(i[0]),time.strftime("%d.%m.%y %H:%M:%S",time.gmtime(i[1])),i[2] dicftp[u1252(i[0])]=(i[1],i[2]) #print i[0],u1252(i[0]),i[1],i[2] envoyer={} import orep lrep=orep.orep(localrep,localdrive,localpath) for i in lrep.afic: if dicftp.has_key(i): if lrep.afic[i][1]!=dicftp[i][1]: envoyer[i]="Taille" if lrep.afic[i][0]>dicftp[i][0]: envoyer[i]="DateTime" else: envoyer[i]="Manque" #for f in envoyer: # print f,envoyer[f] # pass pathlocal=localdrive+localpath+localrep #print 5368,pathlocal flist=envoyer if len(flist)>0: resul=ftpupload() resul=ftpclose() if resul is None: resul="\r\nTranfert terminé.\r\n" ##envoiautoitautomessage(u"MESSAGE|||"+resul.decode('utf-8','replace')) ##envoiautoitautomessage(u"CLOSE|||3000") def thrftpaddfile(chemin="", *fichiers): global tq_ftp,tq_ftpnb,tq_nb,tq_tai #print fichiers, for f in fichiers: #print f, if chemin=="": ch='' fic=f if f.find('\\')>-1: fic=os.path.basename(f) ch=os.path.dirname(f) else: ch=chemin fic=f #print "thrftpaddfile",ch,fic tq_ftp.put((ch,fic)) tq_ftpnb=0 tq_nb=0 def thrftpnb(): global tq_ftp,tq_ftpnb,tq_nb,tq_nb return tq_ftp.qsize()+tq_ftpnb #return tq_ftpnb def thrftprun(): pth=threading.Thread(target=thrftp) #print "thrftp" pth.setDaemon(True) pth.start() def thrftp(): global tq_ftp,tq_ftpnb,tq_nb,tq_tai,host,port,login,pwd,path #print "Len",tq_ftp.qsize() import stat if not tq_ftp.empty(): autoitautomessageload(dureemax=15000) connexion = ftplib.FTP() connexion.connect(host, port) connexion.getwelcome( ) connexion.login(login, pwd) connexion.cwd(path) sst= "Le serveur répond : "+str(connexion.getwelcome()) #envoiautoitautomessage("MESSAGE|||"+sst.decode('utf-8','replace')) msg= _(sst) #print sst vifi(msg) while 1: try: chemin,fichier=tq_ftp.get(False) if chemin.startswith('.'): chemin=chemin[1:] if chemin.startswith('\\'): chemin=chemin[1:] if chemin.startswith('\\'): chemin=chemin[1:] tq_ftpnb+=1 numth=tq_ftpnb except: #print"Rien à envoyer" break if chemin=='': gfichier=fichier else: gfichier=chemin+'\\'+fichier #print numth,gfichier, #time.sleep(2) f = open(gfichier,"rb") #print '->', if chemin=='': connexion.cwd(path) else: try: connexion.cwd(path+'/'+chemin) except: vifi('FTP DIR-problem ; path: '+path+' chemin: '+chemin) envoiautoitautomessage("MESSAGE|||FTP DIR-problem ; path: "+path+' chemin: '+chemin) return envoiautoitautomessage("MESSAGE||| "+fichier+" "+str(numth)+" / Total: "+str(tq_tai)) connexion.storbinary("STOR " + fichier, f, 8192) tq_nb+=1 tq_tai+=os.stat(gfichier)[stat.ST_SIZE] #envoiautoitautomessage("MESSAGE||| "+fichier+" ("+str(numth)+") : Ok. Total: "+str(tq_nb)+" / "+str(tq_tai)+". Reste:"+str(tq_ftpnb)) vifi(_("Envoi (upload) du fichier ")+fichier+" ("+str(numth)+") : Ok. Total: "+str(tq_nb)+" / "+str(tq_tai)+". Reste:"+str(tq_ftpnb)) #print numth,'.('+fichier+').',' ',tq_ftpnb f.close() tq_ftpnb-=1 #print tq_ftpnb time.sleep(0.1) #print "\r\nClose FTP" if int(tq_ftpnb)<1: envoiautoitautomessage(u"CLOSE|||2000") connexion.quit() #del(hautoitmessage) #del(autoitprefix) def ftpnlst(): # lit le directory courant depuis le serveur FTP global host,port,login,pwd,path,pathlocal,flist,chaineretour chaineretour='' liste = connftp.nlst() for i in liste: chaineretour=chaineretour+i+'\t' return(liste) #modif ver 3.269 def ftpdecmul(txt,car=None): """ print 4366,txt nomfichier=txt[55:] print nomfichier lst=txt[:55].split(car) lret=[] for i in lst: if i!='': lret.append(i) lret.append(nomfichier) """ lst=txt.split(car) nomfichier=' '.join(lst[8:]) #print nomfichier lret=lst[:8] lret.append(nomfichier) return lret #modif 3.19 def ftpstodir(txt): global host,port,login,pwd,path,pathlocal,flist,connftp,GlobalPARAMliste,GlobalPARAMlisteindexRetour mois={'Jan':1} mois['Feb']=2 mois['Mar']=3 mois['Apr']=4 mois['May']=5 mois['Jun']=6 mois['Jul']=7 mois['Aug']=8 mois['Sep']=9 mois['Oct']=10 mois['Nov']=11 mois['Dec']=12 li=ftpdecmul(txt) #print " Taille:",li[4], #print " Mois:",mois[li[5]], #print " Jour:"+li[6], a=datetime.datetime.now().year hh=23 mn=59 if li[7].find(':')>-1: hh=int(li[7].split(':')[0]) mn=int(li[7].split(':')[1]) #print " Heure:",li[7], else: a=int(li[7]) #print " Annee:",li[7], #dat=li[6]+"."+li[5]+"."+a datim=time.mktime((a, mois[li[5]], int(li[6]), hh, mn, 00, 0, 0, 0)) #print " Fichier:"+li[8] #print '-'*44 #vifi(ligne) ali=(li[8],datim,int(li[4])) #print ali #msginfo("ali",str(ali)) GlobalPARAMliste.append(ali) #print GlobalPARAMliste return li[8],datim,int(li[4]) def ftpdir(*argu): # lit le directory courant depuis le serveur FTP global host,port,login,pwd,path,pathlocal,flist vifi(connftp.dir(argu)) def plitnews(): global newsserver,newsport,newsuser,newspasse,groupname,pdestination,newspremier,newsdernier if not os.path.isdir(pdestination): os.mkdir(pdestination) destination = pdestination+'\\'+groupname+'\\' vifi(_('destination : ')+destination) if not os.path.isdir(destination): os.mkdir(destination) vifi(_('Connexion au serveur de News ')+newsserver+" / "+newsuser) try: if newsuser<>'' : ns = nntplib.NNTP(newsserver,newsport,newsuser,newspasse) else: ns = nntplib.NNTP(newsserver) except: vifi(_('Ne peut se connecter au serveur de news ')+newsserver) else: vifi(_('Le serveur de News est connecté et répond ')+ns.getwelcome()) vifi(_("Tentative d'accès au groupe ")+groupname) try: group = ns.group(groupname) except: vifi(_('Ne peut pas ouvrir le groupe ')+groupname) else: vifi('Ok.') count = group[1] # nb d'articles sur le server first = group[2] # ID du 1er article disponible last = group[3] # ID du dernier article disponible sfirst = newspremier if sfirst==0: sfirst = first slast = newsdernier if slast==0: slast = last vifi(_("Nb d'Articles ")+str(count)+' '+_('Premier ')+str(first)+' '+_('Dernier ')+str(last)) if (sfirst >= int(first)) and (sfirst <= int(last)): first = str(sfirst) for articleNumber in range(int(sfirst),int(slast)+1): tmp = str(articleNumber) while tmp.startswith(' '): tmp=tmp[1:] while tmp.endswith(' '): tmp=tmp[:-1] filename = destination+tmp+".nws" if not os.path.isfile( filename ): vifi(_("Lecture article ")+str(articleNumber)+' '+_('sur')+' '+str(slast)) try: article = ns.article(str(articleNumber)) except: vifi(" "+_("Ne peut lire l'article")+str(articleNumber)) else: f=open(filename, 'w+') for line in article[3]: f.write(line+'\n') f.close() vifi(_('Fermeture connexion serveur de news...')) ns.quit() def dlitnews(newsserver,newsport,newsuser,newspasse,groupname,pdestination,newspremier,newsdernier): """ lit un ensemble de messages d'un newsgroup et les enregistre dans le dossier pdestination\newsgroup retourne une liste des (n°) messages reçus """ if not os.path.isdir(pdestination): os.mkdir(pdestination) destination = pdestination+'\\'+groupname+'\\' lret=[] vifi(_('destination : ')+destination) if not os.path.isdir(destination): os.mkdir(destination) vifi(_('Connexion au serveur de News ')+newsserver+" / "+newsuser) try: if newsuser<>'' : ns = nntplib.NNTP(newsserver,newsport,newsuser,newspasse) else: ns = nntplib.NNTP(newsserver) except: vifi(_('Ne peut se connecter au serveur de news ')+newsserver) else: vifi(_('Le serveur de News est connecté et répond ')+ns.getwelcome()) vifi(_("Tentative d'accès au groupe ")+groupname) try: group = ns.group(groupname) except: vifi(_('Ne peut pas ouvrir le groupe ')+groupname) else: vifi('Ok.') count = group[1] # nb d'articles sur le server first = group[2] # ID du 1er article disponible last = group[3] # ID du dernier article disponible sfirst = newspremier if sfirst==0: sfirst = first slast = newsdernier if slast==0: slast = last vifi(_("Nb d'Articles ")+str(count)+' '+_('Premier ')+str(first)+' '+_('Dernier ')+str(last)) if (sfirst >= int(first)) and (sfirst <= int(last)): first = str(sfirst) for articleNumber in range(int(sfirst),int(slast)+1): tmp = str(articleNumber) while tmp.startswith(' '): tmp=tmp[1:] while tmp.endswith(' '): tmp=tmp[:-1] filename = destination+tmp+".nws" if not os.path.isfile( filename ): vifi(_("Lecture article ")+str(articleNumber)+' '+_('sur')+' '+str(slast)) try: article = ns.article(str(articleNumber)) except: vifi(" "+_("Ne peut lire l'article")+str(articleNumber)) else: f=open(filename, 'w+') for line in article[3]: f.write(line+'\n') f.close() lret.append(articleNumber) vifi(_('Fermeture connexion serveur de news...')) ns.quit() return lret def dlitlistnews(newsserver,newsport,newsuser,newspasse,pgroupname,pdestination,lmsg): """ lit un ensemble de messages d'un newsgroup et les enregistre dans le dossier pdestination\newsgroup retourne une liste des (n°) messages reçus """ autoitautomessageload() groupname=pgroupname if type(groupname) is types.UnicodeType: groupname=groupname.encode('cp1252','ignore') if not os.path.isdir(pdestination): os.mkdir(pdestination) destination = pdestination+'\\' lret=[] vifi(_('destination : ')+destination) envoiautoitautomessage("MESSAGE|||"+_('destination : ')+destination) vifi(_('Connexion au serveur de News ')+newsserver+" / "+newsuser) envoiautoitautomessage("MESSAGE|||"+_('Connexion au serveur de News ')+newsserver+" / "+newsuser) try: if newsuser<>'' : ns = nntplib.NNTP(newsserver,newsport,newsuser,newspasse) else: ns = nntplib.NNTP(newsserver) except: vifi(_('Ne peut se connecter au serveur de news ')+newsserver) envoiautoitautomessage("MESSAGE|||"+_('Ne peut se connecter au serveur de news ')+newsserver) else: vifi(_('Le serveur de News est connecte et repond ')+ns.getwelcome()) envoiautoitautomessage("MESSAGE|||"+_('Le serveur de News est connecte et repond ')+ns.getwelcome()) #vifi(_("Tentative d'acces au groupe ")+groupname) #envoiautoitautomessage("MESSAGE|||"+_("Tentative d'acces au groupe ")+groupname) try: group = ns.group(groupname) except: try: vifi(_('Ne peut pas ouvrir le groupe ')+groupname) envoiautoitautomessage("MESSAGE|||"+_('Ne peut pas ouvrir le groupe ')+groupname) except: vifi(_('Ne peut pas ouvrir le groupe ')) envoiautoitautomessage("MESSAGE|||"+_('Ne peut pas ouvrir le groupe ')) else: vifi('Ok.') envoiautoitautomessage("MESSAGE|||ok.") count = group[1] # nb d'articles sur le server first = group[2] # ID du 1er article disponible last = group[3] # ID du dernier article disponible for articleNumber in lmsg: if (articleNumber >= int(first)) and (articleNumber <= int(last)): tmp = str(articleNumber) while tmp.startswith(' '): tmp=tmp[1:] while tmp.endswith(' '): tmp=tmp[:-1] filename = destination+tmp+".nws" if not os.path.isfile( filename ): vifi(_("Lecture article ")+str(articleNumber)) envoiautoitautomessage("MESSAGE|||"+_("Lecture article ")+str(articleNumber)+' (=> '+last+' )') try: article = ns.article(str(articleNumber)) except: vifi(" "+_("Ne peut lire l'article")+str(articleNumber)) envoiautoitautomessage("MESSAGE|||"+_(" article non disponible")+" "+str(articleNumber)) else: f=open(filename, 'w+') for line in article[3]: f.write(line+'\n') f.close() lret.append(articleNumber) vifi(_('Fermeture connexion serveur de news...')) envoiautoitautomessage("MESSAGE|||"+_('Fermeture connexion serveur de news...')) ns.quit() envoiautoitautomessage("CLOSE|||1000") vifi('END') return lret def composemsgnews(newsgroup, sdate, ssujet, piecesj=[],nfrom="xxx ",nreply="xxx ", newswriter='Ponx_NewsWriter',reference=None, xfacedata=None): smessage=GlobalPARAM[0] #.encode(CodingParDefaut,'replace') if smessage.find("-1 or smessage.find("-1: mode="HTML" smessagehtml=smessage smessage="Ce message est en HTML. Veuillez utilisez un lecteur de news capable de lire le HTML, afin de voir le message entier." msg=prepmailhtml('NEWS',nfrom, newsgroup, piecesj, ssujet, smessage, smessagehtml, newswriter, reference, sdate, xfacedata) else: mode="TEXT" smessagehtml='' msg=prepmailtext('NEWS', nfrom, newsgroup, piecesj, ssujet, smessage,newswriter,reference, sdate, xfacedata) if msg is None: return(None) else: #print mode return(msg) def composemsgnewsOLD20081123(newsgroup, sdate, ssujet, piecesj=[],nfrom="xxx ",nreply="xxx "): smessage=GlobalPARAM[0].encode(CodingParDefaut,'replace') #print re.search("[]: mode="HTML" else: mode="TEXT" #print mode chr=re.findall('[cCdDeE]:\\\\+.*["]',smessage) numid=1000 pieinternes=[] for ID in chr: if ID[-1]==">": ID=ID[:-1] if ID[-1]=='"': ID=ID[:-1] #print ID numid=numid+1 rempl='PONX-ponx.org-'+str(numid)[1:] #print"rempl",rempl pieinternes.append((ID,rempl)) smessage=string.replace(smessage,ID,'cid:'+rempl) #print txt for item in pieinternes: #print item pass try: msgfichier = open("c:/PonxNews.nws","wb") #msgfichier = tempfile.TemporaryFile() # Write mail message to temp file. except: time.sleep(1) msgfichier = open("c:/PonxNews.nws","wb") mime = MimeWriter.MimeWriter(msgfichier) #mime.addheader("Reply-To", nreply) mime.addheader("From", nfrom) mime.addheader("Newsgroups", newsgroup) mime.addheader("Subject", ssujet) #jour=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"] #mois=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] mime.addheader("Date",sdate) mime.addheader("MIME-Version", "1.0") mime.addheader("Sender","VladimirSukoi@aquablue.grizzlydev.com") mime.addheader("X-Newswriter","Ponx based script") mime.addheader("Face","iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAMFBMVEUAAP8A/wD/AAD///8S86ThOKt0GegAAA8AAADhOLsAAAAAAAAAAAAAAAAS8/wTAABMGR5nAAAABHRSTlP///8AQCqp9AAAAOVJREFUeNp1ktsRhCAMReO1Ae1gS3Bn+++BChxLoAFg5WUSCfkAk3ByhhH6TYL4c9/3jTNQj5gX96TcyOHJaFx5CTaRyCBi3ZxJeIu46hYsQiqeRuwFZxDeIq5eCCOhFL0RueIGwltEU3xYwkTSPN6KLuEzPiefF3FJImgiFTc0oRRNAqUglmBQNAmE4isnYFRUCVix0iYkGBVVAlYctIgRMBRF0g4s91M/z9OzBIaiSDAU0TepSCwZiSaBVvQHESyilqBvwRKDqBLkq4nggctEYo3KcaD8BEMyIda7MZFMiCM3bMkf4YdDp1OGyG0AAAAASUVORK5CYII=") mime.flushheaders() if mode=="HTML": mime.startmultipartbody("alternative") mime.addheader("Content-Transfer-Encoding", "quoted-printable") #------------------------------------message lui-même if mode=="HTML": part = mime.nextpart() msgfichier = mime.startbody("text/html", [("charset","Windows-1252")]) else: msgfichier.write('\n') tempmsg=quopri.encodestring(smessage) tempmsg=tempmsg.replace(' ','   ') tempmsg=tempmsg.replace(' ','  ') #print tempmsg msgfichier.write(tempmsg+'\r\n') #------------------------------------------- ajout des pièces jointes (fichiers) for pie in piecesj: if os.path.isfile(pie): f = open(pie,'rb') type,encoding = mimetypes.guess_type(f.name) if not type: type = "application/octet-stream" part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "base64") msgfichier = part.startbody(type, [("name", os.path.basename(f.name))]) base64.encode(f, msgfichier) #------------------------------------------- ajout des pièces jointes internes (fichiers) for pie,ID in pieinternes: if os.path.isfile(pie): f = open(pie,'rb') type,encoding = mimetypes.guess_type(f.name) if not type: type = "application/octet-stream" part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "base64") part.addheader("Content-ID","<"+ID+">") msgfichier = part.startbody(type, [("name", os.path.basename(f.name))]) base64.encode(f, msgfichier) if mode=="HTML": mime.lastpart() else: msgfichier.write('\n') msgfichier.flush() msgfichier.seek(0) msgfichier.close() def pecritnews(newsserver, port, user, passe, groupname, sdat, ssujet, piecesjointes, nfrom="ponx@NoSPAM.NoSpam.com", nreply="ponx@NoSPAM.NoSpam.com"): msg=composemsgnews(groupname, sdat, ssujet, piecesjointes, nfrom, nreply) try: if msg is None: return(False) if msg.flag==False: return(False) except: pass f = open("C:/PonxNews.nws","w") f.write(uutf8(msg)) f.close() vifi(_('Connexion au serveur de News ')+newsserver) try: if user<>"": ns = nntplib.NNTP(newsserver,port,user,passe) else: ns = nntplib.NNTP(newsserver) except: vifi(_('Ne peut se connecter au serveur de news ')+newsserver) else: vifi(_('Le serveur de News est connecté et répond ')+ns.getwelcome()) vifi(_("Tentative d'accès au groupe ")+groupname) try: group = ns.group(groupname) except: vifi(_('Ne peut pas ouvrir le groupe ')+groupname) else: vifi('Ok.') try: f = open('c:/PonxNews.nws') sret=ns.post(f) f.close() vifi(sret) except nntplib.NNTPError, err: vifi(err.response) vifi(_("Erreur d'envoi du message sur le groupe ")+groupname) else: vifi(_('Message envoyé.')) vifi(_('Fermeture connexion serveur de news...')) ns.quit() try: os.remove("c:\\PonxNews.nws") except: pass #*** NEW *** def pecritnewsmass1(newsserver, port, user, passe, groupname, nfrom="xxx ", nreply="xxx "): global ns,group,chaineretour chaineretour="" vifi(_('Connexion au serveur de News ')+str(newsserver)) try: nomgroupe=str(groupname) except: nomgroupe=" " try: if user<>"": ns = nntplib.NNTP(str(newsserver),int(port),str(user),str(passe)) else: ns = nntplib.NNTP(str(newsserver)) except: vifi(_('Ne peut se connecter au serveur de news ')+str(newsserver)) return chaineretour vifi(_('Le serveur de News est connecte et repond ')+ns.getwelcome()) vifi(_("Tentative d'acces au groupe ")+repr(nomgroupe)) group="xxx" try: group = ns.group(groupname) vifi(str(group)[-120:]) except: vifi(_('Ne peut pas ouvrir le groupe ')+repr(nomgroupe)) return chaineretour #*** NEW *** def pecritnewsmass2(pgroupname, sdat, ssujet, piecesjointes, nfrom="xxx ", nreply="xxx ",newswriter='Ponx_NewsWriter', reference=None, xfacedata=None): global ns,group try: nomgroupe=str(pgroupname) except: nomgroupe=" " sret="" groupname=uutf8(pgroupname) #06.01.2012 msg=composemsgnews(groupname, sdat, ssujet, piecesjointes, nfrom, nreply, newswriter, reference, xfacedata) msg=uutf8(msg) #06.01.2011 try: if msg is None: return(False) if msg.flag==False: return(False) except: pass msg=msg.replace('\\n','\n') msg=msg.replace("\'","'") try: open('c:/PonxNews.nws','wb').write(msg) time.sleep(0.1) f = open('c:/PonxNews.nws') sret=ns.post(f) f.close() vifi(sret) except: #except nntplib.NNTPError,err: #vifi(err.response) #lié à l'option ci-dessus sret=_("Erreur d'envoi du message sur le groupe ")+nomgroupe vifi(sret) else: sret=_('Message envoyé.') vifi(sret) try: #os.remove("c:\\PonxNews.nws") pass except: pass return sret #*** NEW *** def pecritnewsmass3(): global ns,group try: ns.quit() except: pass def plstgrpnews(): """ retourne la liste (de tuples) des groupes : (nom_groupe, premier_message_disponible, dernier_message, envoi_autorise) """ global newsserver,newsport,newsuser,newspasse try: if newsuser<>'' : ns = nntplib.NNTP(newsserver,newsport,newsuser,newspasse) else: ns = nntplib.NNTP(newsserver) reponse, liste = ns.list() vifi(_('Serveur de News ')+newsserver) for i in liste: vifi(str(i[0])+' '+str(i[1])+' messages.') except socket.error: vifi(_('Impossible de se connecter au serveur : ')+newsserver) ns.quit() def dlstgrpnews(newsserver,newsport,newsuser,newspasse): """ retourne la liste (de tuples) des groupes : (nom_groupe, premier_message_disponible, dernier_message, envoi_autorise) """ liste=[] try: if newsuser<>'' : ns = nntplib.NNTP(newsserver,newsport,newsuser,newspasse) else: ns = nntplib.NNTP(newsserver) reponse, liste = ns.list() vifi(_('Serveur de News ')+newsserver) for i in liste: vifi(str(i[0])+' '+str(i[1])+' messages.') except socket.error: vifi(_('Impossible de se connecter au serveur : ')+newsserver) ns.quit() return liste def dpargroup(newsserver,newsport,newsuser,newspasse,newsgroup): nb = first = last = 0 nom='' ngroupe=newsgroup autoitautomessageload() envoiautoitautomessage("MESSAGE|||Tentative de connexion au serveur "+str(newsserver)) if type(ngroupe) is types.UnicodeType: ngroupe=ngroupe.encode('cp1252','ignore') #msginfo('6244','dpargroup') try: if newsuser<>'' : ns = nntplib.NNTP(newsserver,newsport,newsuser,newspasse) else: ns = nntplib.NNTP(newsserver) reponse, nb, first, last, nom = ns.group(ngroupe) #msginfo(str(first),str(last)) #msginfo(str(nom),str(nb)) except socket.error: vifi(_('Impossible de se connecter au serveur : ')+newsserver) ns.quit() return nb, first, last, nom def decodesujetunitaire(txt, typ='Subject: '): if txt[:len(typ)]!=typ: txt=typ+txt hcodage=None try: lsuj=email.Header.decode_header(txt) hcodage = None if len(lsuj)>1: hcodage = lsuj[1][1] sujet=lsuj[1][0] else: sujet=lsuj[0][0][9:] except: lsuj=txt sujet=lsuj try: if hcodage is None: suj=unicode(sujet) else: if hcodage=="x-gbk": hcodage="gbk" suj=sujet.decode(hcodage,'replace') except: #msginfo("6461",str(hcodage)) try: suj=unicode(sujet,hcodage,'replace') except: suj=unicode(sujet,'cp1252','ignore') return suj #,hcodage) #*** MODIF *** meilleur décodage def decodesujetOLD(txt,typ='Subject: '): sret=u'' pointeur=0 while 1: i=string.find(txt,'=?') if i>-1: sret+=txt[:i] j=string.find(txt,'?=',i) k=j while k>-1: k=string.find(txt,'?=',j+2) if k>-1: j=k #k=string.find(txt,'?Q?',j-3) #if k>-1 and ki: ss=decodesujetunitaire(txt[i:j+2],typ) sret+=ss if txt[j:j+4]=='?= =': txt=txt[j+3:] else: txt=txt[j+2:] else: sret+=txt txt=[] else: try: sret+=txt except: try: sret+=str(txt) except: sret+=txt.decode('utf-8','ignore') break return sret #*** MODIF *** meilleur décodage def decodesujet(txt,typ='Subject: '): sret=u'' pointeur=0 while 1: try: i=string.find(txt,'=?') except: try: i=string.find(str(txt),'=?') except: i=-1 if i>-1: sret+=txt[:i] j=string.find(txt,'?=',i) if j>i: if txt[j-2:j+2]=="?Q?=" or txt[j-2:j+2]=="?q?=" : j=string.find(txt,'?=',j+2) if j>i: ss=decodesujetunitaire(txt[i:j+2],typ) sret+=ss txt=txt[j+2:] else: sret+=txt txt=[] else: try: sret+=txt except: try: sret+=str(txt) except: sret+=txt.decode('cp1252','ignore') #sret+=txt.decode('utf-8','ignore') break return sret def ppopnbmsg(spop, popusr, motdepass, *bof, **kbof): try: serveur = poplib.POP3(spop) rep = serveur.getwelcome() rep = serveur.user(popusr) rep = serveur.pass_(motdepass) nbm, tai = serveur.stat() except: return None return nbm,tai def ppoplitsauve(nom, spop, popusr, motdepass, dossdestination='D:\\niouzart\\boitereception', messageaffiche=False): """ Lit, sur Internet, tous les messages disponibles pour un compte, et les enregistre dans dossdestination, sous le nom de fichier [nom]_dateheure.eml Retourne la liste des messages/fichiers reçus. """ global globalautomessage try: temp=globalautomessage except: if messageaffiche: globalautomessage=automessage() lmessages=[] #try: if True: serveur = poplib.POP3(spop) rep = serveur.getwelcome() vifi('Server: '+rep) rep = serveur.user(popusr) vifi('User: '+rep) rep = serveur.pass_(motdepass) vifi('Password: '+str(rep)) nbm, tai = serveur.stat() vifi('Nb messages: '+str(nbm)) """ except: messageboxduree(titre='ppoplit '+spop,texte=chaineretour, duree=3) return lmessages #si erreur """ num = 0 while num '': if st[0:4] == 'From': try: try: exp = str(decodesujet(st,'From: ')[6:].encode('cp1252','replace')) except: exp = decodesujet(st,'From: ')[6:] except: exp = 'xxx' if st[0:7]=='Subject'>0: suj=st if len(msg)>numheader: try: if msg[numheader+1][0]==' ' or msg[numheader+1][0]=='\t': st+=str(msg[numheader+1]) else: st=suj except: st=suj try: sujencodage='' if suj.find('=?')>-1: tempi=suj.find('=?') tempj=suj.find('?',tempi+2) sujencodage=suj[tempi+2:tempj] try: suj = str(decodesujet(st,'Subject: ')[9:].encode('cp1252','replace')) except: suj = decodesujet(st,'Subject: ')[9:] except: suj = 'Sujet indéterminé' if st[0:4] == 'Date': try: try: dat = str(decodesujet(st,'Date: ')[6:].encode('cp1252','replace')) except: dat = decodesujet(st,'Date: ')[6:] except: dat = 'Xxx, 00 Dec 2999 00:00:00 +0000' if st[0:12] == 'Content-Type': typ=str(st[14:].encode('cp1252','replace')) except: pass vifi(_('Erreur')+' '+_('sur')+' msg '+str(num)) try: #print "Message",num,'\t',suj vifi('|'+str(num)+SEPARITEMSERIAL+str(tai)+SEPARITEMSERIAL+exp+SEPARITEMSERIAL+suj+SEPARITEMSERIAL+dat+SEPARITEMSERIAL+typ+SEPARITEMSERIAL+sujencodage+chr(255)) lmessages.append([num,tai,exp,suj,dat,typ,sujencodage]) except: pass vifi(_('Erreur')+' '+_('sur')+' vifi '+str(num)) try: if mode!='TETE': smsg=string.join(msg,'\r\n') GlobalPARAM.append(smsg) except: pass vifi(_('Erreur')+' '+_('sur')+' GlobalPARAM '+str(num)) #retourne \t n°message \t taille \t expéditeur \t sujet (objet) \t date \t typ [\t message] \255 # [\t message] uniquement si mode!='tete' serveur.quit() GlobalPARAMindexRetour=0 return lmessages def cpoplit(compte, mode='TETE'): import pasram lret=[] if compte=="TOUS": for cpt in pasram.pop: #print cpt lret.extend(ppoplit(pasram.pop[cpt]['serveur'], pasram.pop[cpt]['utilisateur'], pasram.pop[cpt]['password'], mode)) else: #msginfo("5651",pasram.pop[compte]['utilisateur']) lret.extend(ppoplit(pasram.pop[compte]['serveur'], pasram.pop[compte]['utilisateur'], pasram.pop[compte]['password'], mode)) return lret def getpasramproperty(compte, propname='adr'): import pasram return pasram.pop[compte][propname] def ppopdestroy(spop, popusr, motdepass, listemsg): serveur = poplib.POP3(spop) rep = serveur.getwelcome() vifi('Server : '+rep) rep = serveur.user(popusr) vifi('User : '+rep) rep = serveur.pass_(motdepass) vifi('Password: '+rep) for num in listemsg: retv = serveur.dele(int(num)) vifi(_("suppression du message ")+str(num)+" "+str(retv)) serveur.quit() def cpopdestroy(compte, listemsg): import pasram ppopdestroy(pasram.pop[compte]['serveur'], pasram.pop[compte]['utilisateur'], pasram.pop[compte]['password'], listemsg) def sendmessage(sender, recipients, msg, host, user=None, password=None, port=25): """ server = smtplib.SMTP(host,port) if not(user is None): server.login( user, password) server.set_debuglevel(0) time.sleep(0.1) if type(recipients) in (types.StringType,types.UnicodeType): recipients=[recipients] dest=string.join(recipients,';') msginfo("sender",sender) msginfo("dest",dest) msginfo("msg",msg) server.sendmail(sender, dest, msg) server.quit() """ try: server = smtplib.SMTP(host,port) if not(user is None): server.login( user, password) server.set_debuglevel(0) time.sleep(0.1) except: vifi(_("Erreur")) return try: if type(recipients) in (types.StringType,types.UnicodeType): recipients=[recipients] dest=string.join(recipients,';') #msginfo("sender",sender) #msginfo("dest",dest) #msginfo("msg",msg) server.sendmail(sender, dest, msg) except smtplib.SMTPServerDisconnected: #msginfo("Error",'SMTPServerDisconnected') vifi('SMTPServerDisconnected') except smtplib.SMTPResponseException: #msginfo("Error",'SMTPResponseException') vifi('SMTPResponseException') except smtplib.SMTPConnectError: #msginfo("Error",'SMTPConnectError') vifi('SMTPConnectError') except smtplib.SMTPHeloError: #msginfo("Error",'SMTPHeloError') vifi('SMTPHeloError') except smtplib.SMTPSenderRefused: #msginfo("Error",'SMTPSenderRefused') vifi('SMTPSenderRefused') except smtplib.SMTPRecipientsRefused: #msginfo("Error",'SMTPRecipientsRefused') vifi('SMTPRecipientsRefused') except smtplib.SMTPDataError: #msginfo("Error",'SMTPDataError') vifi('SMTPDataError') except: #msginfo("Error","Erreur dans l'envoi mail") vifi(_("Erreur dans l'envoi mail")) server.quit() def sendmessageOLD(sender, recipients, msgfile, host, user=None, password=None): smtp = smtplib.SMTP(host or 'localhost') if not(user is None): smtplib.login( user, password) #smtp.putcmd("helo",host) code,resp = smtp.getreply() if code <> 250: smtp.rset() #raise "Server greeting error" vifi(_("Erreur")+":acces denied.") smtp.quit() return code,resp = smtp.mail(sender) if code <> 250: smtp.rset() #raise smtplib.SMTPSenderRefused vifi(_("Erreur")+":sender refused.") smtp.quit() return errs = {} for recipient in recipients: code,resp = smtp.rcpt(recipient) if code <> 250 and code <> 251: errs[recipient] = (code,resp) if len(errs) == len(recipients): # Server refused all recipients. smtp.rset() #raise smtplib.SMTPRecipientsRefused vifi(_("Erreur")+":recipient(s) refused.") smtp.quit() return # Send contents of message file. smtp.putcmd("data") code,resp = smtp.getreply() if code <> 354: smtp.rset() #raise smtplib.SMTPDataError vifi(_("Erreur")+":"+_("Erreur")+" of data-transfert.") smtp.quit() return while 1: s = msgfile.read(1024) # BLK_SIZE = 1024 if not s: break smtp.send(s) smtp.send("\n.\n") # Message termination string. code,resp = smtp.getreply() if code <> 250: smtp.rset() #raise smtplib.SMTPDataError vifi(_("Erreur")+":"+_("Erreur")+" of data-transfert.") smtp.quit() return # finally: smtp.quit() def htdecode(a, Remove_SCRIPT='YES', Remove_STYLE='YES', Remove_HEAD='YES'): a=re.sub(' ', ' ',a) a=re.sub('=20', ' ',a) a=re.sub('=3D', '=',a) if Remove_SCRIPT=='YES': i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+10:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+10:] if Remove_STYLE=='YES': i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+9:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+9:] if Remove_HEAD=='YES': i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+8:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+8:] f=cStringIO.StringIO() z=formatter.AbstractFormatter(formatter.DumbWriter(f)) p=htmllib.HTMLParser(z) p.feed(urllib.unquote_plus(a)) p.close() sret=f.getvalue() f.close() return(sret.decode(locale.getpreferredencoding(),'replace')) def addtextOLD20081123(mime, infile): '''Use mime writer to append text part to message. Used to add message body in first MIME message part.''' part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "iso-8859-15") sss=string.join(infile.readlines()) if string.find(sss,'',0,400)>-1: outfile = part.startbody("text/html", [("charset","Windows-1252")]) else: outfile = part.startbody("text/plain", [("charset","Windows-1252")]) # while 1: # s = infile.read(1024) # BLK_SIZE = 1024 # if not s: break outfile.write(sss+'\r\n') def addfileOLD20081123(mime, infile, mimetype=None): '''Use mime writer to append MIME encoded file as message part.''' if not mimetype: type,encoding = mimetypes.guess_type(infile.name) if not type: type = "application/octet-stream" else: type = mimetype part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "base64") outfile = part.startbody(type, [("name", os.path.basename(infile.name))]) base64.encode(infile, outfile) def xface_decode(data,fichier="D:\\niouzart\\faces\\niouzart.png"): ''' Re-crée le fichier .png correspondant à la chaine MIMI (Base-64) d'un message. ''' out=base64.b64decode(data) open(fichier,"wb").write(out) def xface_decode_bmp(data,fichier="D:\\niouzart\\faces\\niouzart"): ''' Re-crée le fichier .bmp correspondant au .png de la chaine MIMI (Base-64) d'un message. ''' try: out=base64.b64decode(data) open(fichier+'.png',"wb").write(out) import Image img = Image.open(fichier+'.png') img.save(fichier+'.bmp') return(True) except: pass return(False) def xface_decode_gif(data,fichier="D:\\niouzart\\faces\\niouzart"): ''' Re-crée le fichier .gif correspondant au .png de la chaine MIMI (Base-64) d'un message. ''' try: out=base64.b64decode(data) open(fichier+'.png',"wb").write(out) import Image img = Image.open(fichier+'.png') img.save(fichier+'.gif') return(True) except: pass return(False) def xface_encode(fichier="D:\\niouzart\\faces\\niouzart.png"): ''' Encode un fichier .png et retourne la chaine MIMI (Base-64) correspondante. Rappel: 48x48 pixels et 744 octets maxi ''' data=open(fichier,"rb").read() if len(data)>744: print "Trop gros" return base64.b64encode(data) class mel(object): def __init__(self): self.msg="" self.numpart=0 self.derpart='' self.sommaire='' self.boundary='' self.numcid=0 self.flag=True def mfrom(self,adressemel,surnom=''): #voir si plusieurs destinataires def guill(txt,spacefin=' '): if txt=='': vret='' else: vret='"'+txt+'"'+spacefin return vret if surnom is None: txt='<'+adressemel+'>' else: txt=guill(surnom)+'<'+adressemel+'>' tmp = email.mime.text.MIMEText("") tmp['From'] = txt txt=tmp.as_string() art=txt.split('\n') vret='' for l in art: if l.startswith('From: '): vret=l self.msg+=vret+'\n' return vret def mto(self,adressemel,surnom=''): #voir si plusieurs destinataires def guill(txt,spacefin=' '): if txt=='': vret='' else: vret='"'+txt+'"'+spacefin return vret txt=guill(surnom)+'<'+adressemel+'>' tmp = email.mime.text.MIMEText("") tmp['To'] = txt txt=tmp.as_string() art=txt.split('\n') vret='' for l in art: if l.startswith('To: '): vret=l self.msg+=vret+'\n' return vret def mnewsgroup(self,newsgroup,newswriter='Ponx_NewsWriter', xfacedata=None): #voir si plusieurs newsgroups def guill(txt,spacefin=' '): if txt=='': vret='' else: vret='"'+txt+'"'+spacefin return vret txt=newsgroup tmp = email.mime.text.MIMEText("") tmp['Newsgroups'] = txt tmp['X-Newsreader'] = newswriter if xfacedata is not None: tmp['Face'] = xfacedata txt=tmp.as_string() art=txt.split('\n') vret='' for l in art: if l.startswith('Newsgroups: '): vret=l for l in art: if l.startswith('X-Newswriter: '): vret+='\n'+l for l in art: if l.startswith('Face: '): vret+='\n'+l self.msg+=vret+'\n' return vret def msujet(self,txt): tmp = email.mime.text.MIMEText("") ###tmp['Subject'] = txt.encode('utf-8','replace') #tmp['Subject'] = txt vret="Subject: "+txt """ ancien: tmp['Subject'] = email.mime.text.MIMEText(txt,_charset='utf-8') txt=tmp.as_string() art=txt.split('\n') vret='' for l in art: if l.startswith('Subject: '): vret=l """ self.msg+=vret+'\n' return vret def mheader(self,nom,txt): tmp = email.mime.text.MIMEText("") #tmp['Subject'] = txt.encode('utf-8','replace') tmp[nom] = txt txt=tmp.as_string() art=txt.split('\n') vret='' for l in art: if l.startswith(nom+': '): vret=l self.msg+=vret+'\n' return vret def mdate(self, dt=None): if dt is None: locale.setlocale(0,'american') dt=time.strftime("%a, %d %b %Y %H:%M:%S")+" +0%d00" % (1+time.localtime().tm_isdst) locale.setlocale(locale.LC_ALL, "") # French_France.1252 self.msg+='Date: '+dt+'\n' def mdatesimple(self): dt=time.strftime("%a, %d %b %Y %H:%M:%S")+" +0%d00" % (1+time.localtime().tm_isdst) self.msg+='Date: '+dt+'\n' def mbound(self,ctype='text/html',contenu=''): if self.numpart==0: self.msg+="MIME-Version: 1.0\n" self.msg+='''Content-Type: multipart/alternative; .BOUNDARY1.''' self.boundary='''\tboundary="----=_NextPart_000_'''+str(self.numpart+1)+'"\n' self.msg+='''X-Priority: 3 X-MSMail-Priority: Normal X-Unsent: 1 X-MimeOLE: Produced By Microsoft MimeOLE V6.0.6001.18049 This is a multi-part message in MIME format. .SOMMAIRE. ''' self.numpart+=1 #self.numpart+=1 nextpart='------=_NextPart_000_'+str(self.numpart) self.derpart=nextpart self.msg+=nextpart+'\n' self.msg+='''Content-Type: '''+ctype+';\n' if ctype=='text/plain': self.msg+=''' charset="utf-8" Content-Transfer-Encoding: 7bit\n\n''' if ctype=='text/html': #self.numpart+=1 self.msg+=''' charset="utf-8" Content-Transfer-Encoding: quoted-printable\n\n''' try: self.msg+=contenu+'\n' except: self.msg+=contenu.decode('utf-8','ignore')+'\n' def minser(self,fichier,typ='image/jpeg',cid='OUI'): # image/jpeg # audio/mid self.numcid+=1 if self.numpart!=2: self.numpart=2 nextpart='------=_NextPart_000_'+str(self.numpart) self.boundary='''\tboundary="----=_NextPart_000_'''+str(self.numpart)+'"\n' nextpartsuite='------=_NextPart_000_'+str(self.numpart-1) self.sommaire+=nextpart+''' Content-Type: multipart/alternative; boundary="'''+nextpartsuite[2:]+'"\n' else: nextpart='------=_NextPart_000_'+str(self.numpart) self.derpart=nextpart self.msg+=nextpart self.msg+='''\nContent-Type: '''+typ+'''; name="''' sfic=fichier.split('\\')[-1] self.msg+=str(sfic) self.msg+='''" Content-Transfer-Encoding: base64 ''' if cid!='OUI': self.msg+='''Content-ID: ''' else: self.msg+='''Content-Disposition: attachment; filename="'''+fichier.split('\\')[-1]+'''" ''' try: f = open(fichier, 'rb') d64=base64.b64encode(f.read()) img64="\n" for i in range(0,len(d64),76): img64+=d64[i:i+76]+'\n' f.close() self.msg+=img64 except: tfichier=u1252(fichier) msginfo("Problème","Impossible d'ouvrir le fichier "+tfichier) self.flag=False def mfinpart(self): self.msg+='\n'+self.derpart+'--\n\n' def mfinalize(self): self.mfinpart() self.msg = self.msg.replace('.SOMMAIRE.',self.sommaire) self.msg = self.msg.replace('.BOUNDARY1.',self.boundary) #self.msg = self.msg.replace(' ','   ') #self.msg = self.msg.replace(' ','  ') return self.msg def mprint(self): #print self.msg if not os.path.isdir("c:\\mel"): os.mkdir("c:\\mel") f=open("c:\\mel\\mm.eml","w") f.write(self.msg) f.close() def mvisu(self): os.startfile("c:\\mel\\mm.eml") def mrecupmsg(self): return self.msg def datemail(d): """ extrait date/heure d'une chaine (d) formatée selon les habitudes mails/news exemple : s,t = datenew("Tue, 30 Nov 2010 14:01:28 +0100") s => Epoch (nb secondes) ; c-à-d t3=time.mktime(datim) t => date sous la forme : JJ.MM.AA HH:MM:SS ; c-à-d time.strftime("%d.%m.%y %H:%M:%S",datim) et aussi : s même_valeur_que time.mktime([2010,11,30,14,1,28,0,0,0]) """ locale.setlocale(0,'american') #print d i=d.find(',') if i<1: j=d.rfind(':') t1=d[:j+2] try: t1=t1.replace('janv.','Jan') t1=t1.replace('févr.','Feb') t1=t1.replace('mars','Mar') t1=t1.replace('avr.','Apr') t1=t1.replace('Mai','May') t1=t1.replace('juin','Jun') t1=t1.replace('juil.','Jul') t1=t1.replace('août','Aug') t1=t1.replace('sept.','Sep') t1=t1.replace('oct.','Oct') t1=t1.replace('nov.','Nov') t1=t1.replace('déc.','Dec') datim=time.strptime(t1,'%d %b %Y %H:%M:%S') except: datim=time.gmtime() else: signe=d.find(' +') if signe<1: signe=d.find(' -') if signe>1: t1=d[:signe] t2=d[signe+1:signe+6] tz=int(t2)*36 #contient le nb de secondes du timezone else: j=d.rfind(':') t1=d[:j+2] #t1=d t2='' tz=0 try: datim=time.strptime(t1,'%a, %d %b %Y %H:%M:%S') except: try: t1=t1.split(', ')[1] t1=t1.replace('janv.','Jan') t1=t1.replace('févr.','Feb') t1=t1.replace('mars','Mar') t1=t1.replace('avr.','Apr') t1=t1.replace('Mai','May') t1=t1.replace('juin','Jun') t1=t1.replace('juil.','Jul') t1=t1.replace('août','Aug') t1=t1.replace('sept.','Sep') t1=t1.replace('oct.','Oct') t1=t1.replace('nov.','Nov') t1=t1.replace('déc.','Dec') datim=time.strptime(t1,'%d %b %Y %H:%M:%S') except: datim=time.gmtime() t3=time.mktime(datim) #t3+=tz ; si on voulait inclure le timezone (normalement, c'est déjà fait) #datim tuple du datetime vret=time.strftime("%d.%m.%y %H:%M:%S",datim) locale.setlocale(locale.LC_ALL, "") # French_France.1252 return(t3,vret) def prepmailhtml(typ, sender, destinataire, lstpjointes, subject=None, messagetxt='', messagehtml=None, newswriter='Ponx_NewsWriter',reference=None, sdate=None, xfacedata=None, accureception=False): """ tester plusieurs destinataires tester messagetxt multilignes avec accents et car spéciaux. """ listecid={} m=mel() if type(sender) in (types.ListType,types.TupleType): m.mfrom(*sender) #sender,surnom else: m.mfrom(sender) #sender,surnom if typ.upper()=="MAIL": if type(destinataire) in (types.ListType,types.TupleType): m.mto(destinataire[0]) else: m.mto(destinataire) else: m.mnewsgroup(destinataire) m.mheader('X-Newsreader',newswriter) #m.mheader('Face',"iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAMFBMVEUAAP8A/wD/AAD///8S86ThOKt0GegAAA8AAADhOLsAAAAAAAAAAAAAAAAS8/wTAABMGR5nAAAABHRSTlP///8AQCqp9AAAAOVJREFUeNp1ktsRhCAMReO1Ae1gS3Bn+++BChxLoAFg5WUSCfkAk3ByhhH6TYL4c9/3jTNQj5gX96TcyOHJaFx5CTaRyCBi3ZxJeIu46hYsQiqeRuwFZxDeIq5eCCOhFL0RueIGwltEU3xYwkTSPN6KLuEzPiefF3FJImgiFTc0oRRNAqUglmBQNAmE4isnYFRUCVix0iYkGBVVAlYctIgRMBRF0g4s91M/z9OzBIaiSDAU0TepSCwZiSaBVvQHESyilqBvwRKDqBLkq4nggctEYo3KcaD8BEMyIda7MZFMiCM3bMkf4YdDp1OGyG0AAAAASUVORK5CYII=") if xfacedata is not None: m.mheader('Face',xfacedata) if reference: m.mheader('References','<'+reference+'>') #avant : m.msujet(u1252(subject)) # si accents ou car spéciaux, utiliser u'...' #plus maintenant ? m.msujet(subject) # si accents ou car spéciaux, utiliser u'...' #plus maintenant ? if accureception: m.mheader('Disposition-Notification-To',sender) locale.setlocale(0,'american') m.mdate(sdate) locale.setlocale(locale.LC_ALL, "") # French_France.1252 m.mbound('text/plain',messagetxt.encode('utf-8','replace')) try: html=messagehtml.encode('utf-8','ignore') except: try: html=messagehtml.encode('cp1252','ignore') except: html=messagehtml html=html.replace("file:///","") def traitecid(html,nbins=1,chaine=''): long=len(chaine)+1 pos=0 ltmp=[] while True: flag=0 i=html.find(chaine+'"',pos) if i>-1: flag+=1 ii=html.find('http:',i+2) #msginfo('7182','*'+chaine+'*'+str(ii)+'*'+str(i)) if ii<0 or (ii-i)>20: j=html.find('"',i+long) fich = html[i+long:j] if len(fich)>0: if fich in listecid: tempcid=listecid[fich] else: tempcid=nbins listecid[fich]=nbins nbins+=1 ltmp.append(fich) html=html[:i+long]+'cid:x'+str(tempcid)+'x'+html[j:] pos=html.find('"',i+long)+1 if flag==0: break pos=0 while True: flag=0 i=html.find(chaine+"'",pos) if i>-1: flag+=1 ii=html.find('http:',i+2) #msginfo('7208','*'+chaine+'*'+str(ii)+'*'+str(i)) if ii<0 or (ii-i)>20: j=html.find("'",i+long) fich = html[i+long:j] if len(fich)>0: if fich in listecid: tempcid=listecid[fich] else: tempcid=nbins listecid[fich]=nbins nbins+=1 ltmp.append(fich) html=html[:i+long]+'cid:x'+str(tempcid)+'x'+html[j:] pos=html.find("'",i+long)+1 if flag==0: break return html,nbins,ltmp linsert=[] ncid=1 html,ncid,lt=traitecid(html,ncid,'url(') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'URL(') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'background=') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'background= ') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'background =') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'src=') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'src= ') if len(lt)>0: linsert.extend(lt) html,ncid,lt=traitecid(html,ncid,'src =') if len(lt)>0: linsert.extend(lt) if html.find(''+html html=html.replace('=','=3D') m.mbound('text/html',html) ''' flag="0" try: ##m.mbound('text/html',html.encode('utf-8','replace')) #m.mbound('text/html',html.encode('cp1252','replace')) m.mbound('text/html',html) flag="html" except: try: m.mbound('text/html',str(html)) flag="str" except: try: m.mbound('text/html',html) flag="direct" except: m.mbound('text/html',repr(html)[2:-1]) flag="repr" ''' m.mfinpart() for numcid,f in enumerate(linsert): #print 7864,f,numcid+1 m.minser(f,cid=numcid+1) if m.flag == False: return(None) for fic in lstpjointes: #print 6391,fic m.minser(fic,cid='NON') # attachment = pièce jointe = cid='NON' if m.flag == False: return(None) #m.mprint() #m.mvisu() #sys.exit() return m.mfinalize() def prepmailtext(typ, sender, destinataire, lstpjointes, subject=None, messagetxt='', newswriter='Ponx_NewsWriter',reference=None, sdate=None, xfacedata=None, accureception=False): """ tester plusieurs destinataires tester messagetxt multilignes avec accents et car spéciaux. """ import smtplib from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText import email.utils,email.header if len(lstpjointes)>0: msg = MIMEMultipart() msg.set_charset('utf-8') else: #msg = MIMEText(messagetxt.encode('utf-8','replace'),_subtype='plain',_charset='utf-8') msg = MIMEText(messagetxt.encode('utf-8','replace'),_subtype='plain') msg.set_charset('utf-8') if type(sender) in (types.ListType,types.TupleType): msg['From']='"'+str(sender[1])+'"<'+str(sender[0]+'>') #sender,surnom else: msg['From']=str(sender) #sender,surnom if typ.upper()=="MAIL": if type(destinataire) in (types.ListType,types.TupleType): sdest='"'+destinataire[0]+'"<'+destinataire[0]+'>' for d in destinataire[1:]: sdest += ';"'+d+'"<'+d+'>' msg['To']=sdest else: msg['To']=destinataire else: msg['Newsgroups'] = destinataire msg['X-Newsreader'] = newswriter #msg['X-Unsent'] = '1' if xfacedata is not None: msg['Face'] = xfacedata if reference: msg['References']='<'+reference+'>' msg['Subject'] = email.header.Header(subject,'utf-8') #email.utils.quote(subject) if accureception: msg['Disposition-Notification-To']=sender locale.setlocale(0,'american') msg['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S")+" +0%d00" % (1+time.localtime().tm_isdst) locale.setlocale(locale.LC_ALL, "") # French_France.1252 msg.preamble = '' if len(lstpjointes)>0: ##msg.attach(MIMEText(messagetxt.encode('cp1252','replace'),_subtype='text',_charset='utf-8')) msg.attach(MIMEText(messagetxt.encode('utf-8','replace'),_subtype='plain',_charset='utf-8')) ####+++m.mdate() msg.epilogue = '' for fic in lstpjointes: fp = open(fic, 'rb') nomf=os.path.split(fic)[1] img = MIMEImage(fp.read(),_subtype='image',filename=nomf,name=nomf) fp.close() msg.attach(img) vret=msg.as_string() try: if not os.path.isdir("c:\\mel"): os.mkdir("c:\\mel") f=open("c:\\mel\\m1.nws","w") f.write(vret) f.close() except: pass #os.startfile("c:\\mel\\m1.nws") #sys.exit() return vret.decode('utf-8','ignore') # modif 3.283 : meilleur traitement des payloads. def mailfiles(sender, destinataire, lstpjointes, subject=None, message=None, smtpserveur=None, user=None, password=None, port=25, accureception=False): '''Mail list of lstpjointes to list of destinataire with optional subject, message and mail smtpserveur. ATTENTION : pour les payloads, les sources des fichiers doivent être entre guillemets ("") ''' global chaineretour chaineretour='' if message[:200].find("-1 or message[:200].find("-1: mode="HTML" messagehtml=message message='Message en HTML.' else: mode="TEXT" messagehtml='' #try: if True: if mode=="HTML": msg=prepmailhtml('MAIL', sender, destinataire, lstpjointes, subject, message, messagehtml, accureception=accureception) if msg is None: return(False) else: msg=prepmailtext('MAIL', sender, destinataire, lstpjointes, subject, message, accureception=accureception) f = open("C:/PonxMel.eml","w") try: f.write(msg.encode('utf-8','replace')) except: try: f.write(msg.encode('cp1252','replace')) except: try: f.write(msg) except: pass f.close() #time.sleep(0.128) try: vifi(_("Envoi message")) except: pass """ print sender print destinataire print msg print smtpserveur print user print password, port """ sret=sendmessage(sender, destinataire, msg.encode('utf-8','replace'), smtpserveur, user, password, port) #vifi(sret) #print "envoyé" #vifi(_("message envoyé")) """ except: chaineretour=_("Erreur dans l'envoi mail") return False """ return sret def mailliste(sender, retour, destinataire, lstpjointes, subject=None, message=None, smtpserveur=None, user=None, password=None, port=25): global chaineretour listedestinataires=[] listemessages=[] chaineretour='' if message.find("-1 or message.find("-1: mode="HTML" messagehtml=message message='Message en HTML.' else: mode="TEXT" messagehtml='' for d in destinataire: if mode=="HTML": msg=prepmailhtml('MAIL', retour, d, lstpjointes, subject, message, messagehtml) if msg is None: return(False) else: msg=prepmailtext('MAIL', retour, d, lstpjointes, subject, message) listedestinataires.append(d) listemessages.append(msg) try: server = smtplib.SMTP(smtpserveur,port) if not(user is None): smtplib.login( user, password) server.set_debuglevel(0) time.sleep(0.1) except: #print 8331,erreur vifi(_("Erreur")) return("Erreur SMTPlib") nb=0 for d,msg in zip(listedestinataires,listemessages): chaineretour += server.sendmail(retour, d, msg) nb+=1 #print nb,d """ try: for d,msg in zip(listedestinataires,listemessages): server.sendmail(sender, d, msg) except smtplib.SMTPServerDisconnected: vifi('SMTPServerDisconnected') except smtplib.SMTPResponseException: vifi('SMTPResponseException') except smtplib.SMTPConnectError: vifi('SMTPConnectError') except smtplib.SMTPHeloError: vifi('SMTPHeloError') except smtplib.SMTPSenderRefused: vifi('SMTPSenderRefused') except smtplib.SMTPRecipientsRefused: vifi('SMTPRecipientsRefused') except smtplib.SMTPDataError: vifi('SMTPDataError') except: vifi(_("Erreur dans l'envoi mail")) """ server.quit() return chaineretour # modif 3.283 : meilleur traitement des payloads. def mailfilesOLD20081123(sender, destinataire, lstpjointes, subject=None, message=None, smtpserveur=None, user=None, password=None,port=25): '''Mail list of lstpjointes to list of destinataire with optional subject, message and mail smtpserveur. ATTENTION : pour les payloads, les sources des fichiers doivent être entre guillemets ("") ''' try: msgfile = tempfile.TemporaryFile() # Write mail message to temp file. mime = MimeWriter.MimeWriter(msgfile) mime.addheader("To",string.join(destinataire,';')) mime.addheader("From", sender) if subject: vifi("Subject "+subject) mime.addheader("Subject", subject) mime.addheader("MIME-Version", "1.0") mime.startmultipartbody("mixed") #--------détermination--pièces--jointes--internes-------------- if re.search("": ID=ID[:-1] if ID[-1]=='"': ID=ID[:-1] #print ID numid=numid+1 rempl='PONX-ponx.org-'+str(numid)[1:] #print"rempl",rempl pieinternes.append((ID,rempl)) message=string.replace(message,ID,'cid:'+rempl) #print txt for item in pieinternes: #print item pass #---fin--détermination--pièces--jointes--internes-------------- if message: if os.path.isfile(message): f = open(message,'rb') else: f = cStringIO.StringIO(message) addtext(mime, f) f.close() if not lstpjointes: pass else: vifi(_("Ajout piece(s) jointe(s)")) for file in lstpjointes: vifi(file) f = open(file,'rb') addfile(mime, f) f.close() #--------ajout-pièces-jointes-internes-(fichiers)------------- for pie,ID in pieinternes: if os.path.isfile(pie): f = open(pie,'rb') type,encoding = mimetypes.guess_type(f.name) if not type: type = "application/octet-stream" part = mime.nextpart() part.addheader("Content-Transfer-Encoding", "base64") part.addheader("Content-ID","<"+ID+">") msgfichier = part.startbody(type, [("name", os.path.basename(f.name))]) base64.encode(f, msgfichier) #----fin-ajout-pièces-jointes-internes-(fichiers)------------- mime.lastpart() msgfile.flush() # Rewind message file and send contents to mail server. msgfile.seek(0) msg = msgfile.read() msgfile.close() vifi(_("Envoi message")) try: """ print sender print destinataire print msg print smtpserveur print user print password, port """ sendmessage(sender, destinataire, msg, smtpserveur, user, password, port) #print "envoyé" vifi(_("message envoyé")) except: vifi(_("Erreur")) #return msg except: global chaineretour chaineretour=_("Erreur dans l'envoi mail") def mailfilesOLD(sender, destinataire, lstpjointes, subject=None, message=None, smtpserveur=None, user=None, password=None, port=25): '''Mail list of lstpjointes to list of destinataire with optional subject, message and mail smtpserveur.''' msgfile = tempfile.TemporaryFile() # Write mail message to temp file. mime = MimeWriter.MimeWriter(msgfile) vifi("To "+string.join(destinataire,';')) mime.addheader("To",string.join(destinataire,';')) vifi("From"+sender) mime.addheader("From", sender) if subject: vifi("Subject "+subject) mime.addheader("Subject", subject) mime.addheader("MIME-Version", "1.0") mime.startmultipartbody("mixed") # Add text message. if message: if os.path.isfile(message): f = open(message,'rb') else: f = cStringIO.StringIO(message) addtext(mime, f) f.close() # Add lstpjointes. vifi(_("Ajout piece(s) jointe(s)")) if not lstpjointes: pass else: for file in lstpjointes: f = open(file,'rb') addfile(mime, f) f.close() mime.lastpart() msgfile.flush() # Rewind message file and send contents to mail server. msgfile.seek(0) vifi(_("Envoi message")) sendmessage(sender, destinataire, msgfile, smtpserveur, user, password, port) msgfile.close() vifi(_("message envoyé")) def decuus(ch): sret='' for s in string.split(ch,'\n'): #print len(s) sret+=binascii.a2b_uu(s) return(sret) def coduus(ch): sret=binascii.b2a_uu(ch) return(sret) def mmm(): fparam="D:\\niouzart\\win7\\12055.nws" fm = open(fparam,'rb') f = fm.read() fm.close() msginfo(fparam,f) msg = email.message_from_string(f) msginfo(str(type(msg)),msg) return def msgextract(fparam, dirdest=None, attachmentseul=False): """Extraction des elements d'un message. Les parametres sont : - message ou nom_du_fichier contenant le message ; si la longueur du message est inferieure a 120, il s'agit d'un nom de fichier ; sinon la chaine contient le message en entier - directory_de_destination (facultatif) ; si present, les fichiers seront enregistres dans ce repertoire ; sinon, il n'y aura qu'une liste - filtre_attachment (facultatif) ; si True, seules les pieces jointes sont extraites. En retour, on a : - une liste contenant les differents elements extraits du message - la chaine globale 'chaineretour' contient les differents messages Particularites : de une a quatre parties sont ajoutees au message, pour traiter les contenu du message proprement dit : - message_texte contient le message, en texte brut, determine par la fonction ; c-a-d - si le message est en plain/text (texte brut) : le message lui-meme, - si le message est en HTML, la partie plain/text si elle est presente, sinon il est extrait de la partie HTML (text/html). - message_plain-text dans le cas d'un message en HTML, c'est la partie eponyme - message_Html contient le message HTML ; c'est notamment la que l'on trouve les scripts d'animation - message_html_decode ; resultat du decodage de la partie HTML """ def htdecode(a): a=re.sub(' ', ' ',a) a=re.sub('=20', ' ',a) a=re.sub('=3D', '=',a) i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+10:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+10:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+9:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+9:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+8:] i=999 while i>0: i=string.find(a,'1: a=a[:i]+a[j+8:] f=cStringIO.StringIO() z=formatter.AbstractFormatter(formatter.DumbWriter(f)) p=htmllib.HTMLParser(z) p.feed(urllib.unquote_plus(a)) p.close() sret=f.getvalue() f.close() return(sret.decode(locale.getpreferredencoding(),'replace')) msgpart=[] msgtxt=''#message texte brut msgpt='' #plain/text msght='' #html mhdec='' #html decode if len(fparam)<120: fm = open(fparam,'rb') f = fm.read() fm.close() else: f=fparam msg = email.message_from_string(f) num=0 msgptencodage=None msgptdecoded=False contentid=[] mem_charset=None for i in msg.walk(): msgcharset=i.get_charsets()[0] if msgcharset is not None: mem_charset=msgcharset try: msgencodage=i.get_all('Content-Transfer-Encoding')[0] except: msgencodage=None #if i.get_content_subtype()!='related' and i.get_content_subtype()!='plain' and not(i.get_content_subtype() is None) : if i.get_content_subtype()!='related' and i.get_content_subtype()!='plain' and not(i.get_content_subtype() is None) : part=i.get_payload( None, True) if part is not None: num+=1 """ #--------------------si on veut de print-------------- print('-'*50+'part.'+str(num)) print("Type: "+i.get_content_type()) print("Subtype: "+i.get_content_subtype()) try: print("Encoding: "+i.get_all('Content-Transfer-Encoding')[0]) except: print("Encoding: None") try: print("Charset:"+str(i.get_charsets()[0])) except: print("Charset: None") """ name=i.get_filename() if name is None: try: st=i.get_all('Content-Type')[0] ideb=string.find(st,'name="')+6 ifin=string.find(st,'"',ideb) if ideb>5: name=st[ideb:ifin] except: name='' try: contentidtmp='cid:'+str(i.get_all('Content-ID')[0][1:-1]) contentid.append([contentidtmp,str(name)]) except: pass #print("FileName:"+str(name)) #print("size:"+str(len(part))) attachment=False st=i.get_all('Content-Disposition') if st: if string.find(str(st),'attachment')>-1: attachment=True #print("Attachment=>:"+str(attachment)) if not(name is None): name=decodesujet(name,"Name: ") typ=i.get_content_type() try: encodage=i.get_all('Content-Transfer-Encoding')[0] except: encodage=None if typ=='text/plain' and attachment==False: #print"-",part if encodage.lower()=='quoted-printable': msgpt=quopri.decodestring(part) else: msgpt=part msgptencodage=encodage elif (typ.lower()=='text/html' or typ.lower()=='html'): msght=part else: if not name: name = "part_%d" % (num,) if i.get_content_subtype()=='jpeg': name+='.jpg' elif i.get_content_subtype()=='jpg': name+='.jpg' elif i.get_content_subtype()=='gif': name+='.gif' elif i.get_content_subtype()=='gif': name+='.gif' elif i.get_content_subtype()=='audio': name+='.mid' elif i.get_content_subtype()=='mid': name+='.mid' elif i.get_content_subtype()=='wav': name+='.wav' elif i.get_content_subtype()=='text': name+='.txt' if attachmentseul==False or attachment==True : if name is not None: name=string.replace(name,"\r","") name=string.replace(name,"\n","") partie=i.get_all('Content-Transfer-Encoding') msgpart.append((str(num), name, str(partie), part, attachment)) if num==1: try: if msgpt is None: msgpt='' if len(msgpt)<1: msgcharset=i.get_charsets()[0] #msginfo(9316,msgcharset) msgpt=part.decode(msgcharset,'replace').encode('utf-8','replace') msgptencodage=msgencodage msgptdecoded=True except: pass else: pass #print "Part = None" else: part=i.get_payload( None, True) msgptencodage=msgencodage msgptdecoded=False try: msgpt=part.decode(msgcharset,'replace').encode('utf-8','replace') msgptdecoded=True except: msgpt=part if num==0: i=999 a=str(msg) while i>0: num+=1 i=string.find(a,'\r\nbegin') if i>1: l=i+7 k=string.find(a,' ',i+4) k=string.find(a,' ',k+1) l=string.find(a,'\r\n',k+1) name=a[k+1:l] j=string.find(a,'`\r\nend',l+2) if j2: if msgptencodage is None: msgptencodage=msgencodage #msginfo(9392,msgptencodage) try: if msgptencodage.lower()=="quoted-printable": msgtxt=quopri.decodestring(msgpt) else: msgtxt=msgpt except: msgtxt=msgpt if msgptdecoded==False: try: if msgptencodage.lower()=='base64': msgtxt=msgtxt.replace('\r','') msgtxt=msgtxt.replace('\n','') try: msgtxt=base64.decodestring(msgpt) except: msgtxt=str(msgpt) msgtxt=msgtxt.replace('\n','\r\n') #if msgcharset=='utf-8': # msgtxt=msgtxt.decode('utf-8','replace').encode('utf-8','replace') except: pass try: msgtxt=msgtxt.decode(msgcharset,'replace').encode('utf-8','replace') except: pass msgtxt=msgtxt.replace(' ',' ') else: msgtxt=htdecode(msght).encode('utf-8','replace') #iso-8859-15 #msginfo(7990,msgpt) #msginfo(7991,msgtxt) try: msgpt=msgpt.decode(mem_charset.lower(),'replace').encode('utf-8','replace') except: pass try: msgpt=quopri.decodestring(msgpt) except: pass #msginfo(9441,str(mem_charset)) if attachmentseul==False: # 'cp1252' 'iso-8859-15' if len(msgtxt)>0: tmpchaine=msgtxt else: tmpchaine=msgpt tmpchaine=tmpchaine.replace("<","<") tmpchaine=tmpchaine.replace(">",">") tmpchaine=tmpchaine.replace("\r\n","
") tmpchaine=tmpchaine.replace("\n","
") tmpchaine=tmpchaine.replace("
","
\r\n") if msgcharset is None: if mem_charset is None: msgtxthtml='''\r\n''' else: msgtxthtml='''\r\n''' #msgtxthtml='''\r\n''' else: msgtxthtml='''\r\n''' msgtxthtml+="\r\n"+tmpchaine+"\r\n" #msgtxthtml="\r\n"+ch1252html(tmpchaine)+"\r\n" #msgtxthtml="\r\n"+chuhtml(tmpchaine)+"\r\n" msgpart.append(('0', 'h_message.htm', 'Ascii', msgtxthtml,False)) msgpart.append(('0', 'message.txt', 'Ascii', msgtxt,False)) msgpart.append(('0', 'message_plain-text.txt', 'Ascii', msgpt,False)) msgpart.append(('0', 'message.html', 'Html-Ascii', msght,False)) msgpart.append(('0', 'message_decode.html', 'Ascii', mhdec,False)) for num,nom,codage,fichier,attachment in msgpart: if dirdest is None: #print(str(num)+'\t'+str(nom)+'\t'+codage+'\t'+str(len(fichier))+'\tattachment: '+str(attachment)) pass else: if not(nom is None): if os.path.isdir(str(dirdest)): """fdest = open(os.path.join(dirdest,nom), "wb") fdest.write(str(fichier)) fdest.flush() fdest.close() """ nom=nom.replace("%20","") nom=nom.replace(":","") nom=nom.replace("/","") nom=nom.replace("\\","") #msginfo('7541',str(nom)) fdest=None efichier=os.path.join(dirdest,nom) efichier=efichier.replace("%20"," ") try: fdest = open(efichier, "wb") try: fdest.write(str(fichier)) except: pass fdest.flush() fdest.close() except: #print _("Ne peut pas ouvrir ")+str(nom)+_(" dans ")+dirdest pass else: fdest.close() del(fdest) else: #print(str(num)+'\t'+nom+'\t'+codage+'\t'+str(len(fichier))+'\t'+str(attachment)) pass fdest = open(os.path.join(dirdest,'quand.txt'), "w") fdest.write(time.strftime("%d.%m.%Y %H:%M:%S")) fdest.flush() fdest.close() return(msgpart) #*** MODIF *** 24.06.2008 : ajout du paramètre cdir def cmdpp4(lst=None, cdir=None): global chaineretour import types if lst is None: lst=GlobalPARAM[0] if type(lst) is types.StringType: lst=lst.split('\n') if cdir: os.chdir(cdir) a = os.popen4(lst[0]) for i in lst[1:]: if i!='': a[0].write(i+'\r\n') a[0].flush() lret=a[1].readlines() chaineretour=''.join(lret) return lret def cmdpp(srep, lst): global chaineretour,CRLF os.chdir(srep) vifi("Directory : "+srep) lret=[] for i in lst : vifi("Command |"+i) if (i[:3]=='cd ') or (i[:3]=='CD '): os.chdir(i[3:]) vifi('New Dir : '+os.getcwd()) else: a = os.popen(i) a.read llig=string.join(a) lret.extend(llig.split('\n')) vifi(llig) #vifi(string.join(a)) return lret #*** NEW *** 27.9.08 : v.4.007 def cmdone(rep, commande,moderetour="LIST"): #global chaineretour,CRLF os.chdir(rep) xchaineretour=''.join(os.popen(commande)) if moderetour.upper() == "STR": return xchaineretour else: return xchaineretour.split('\n') #*** NEW *** 9.10.05 : v.2.38g def expandenvar(evar): """Retourne la version étendue d'une variable d'environnement """ chaineretour=os.popen4("@echo "+evar)[1].read()[:-1] return chaineretour #*** NEW *** 9.11.05 : v.3.01b02 def findPID(exename): import os a = os.popen4('tasklist /FI "IMAGENAME eq '+exename+'"') a[0].flush() try: info=a[1].readlines()[3].split() except: info=[exename,"NotFound"] return (info[1],info[0]) #*** NEW *** 9.11.05 : v.3.01b02 #*** NEW *** 16.11.05 : v.3.03b05 : ajout du '/F' def killPID(pid): import os a = os.popen4('taskkill /PID '+str(pid)+' /F') a[0].flush() #*** NEW *** 5.4.06 : v.3.18 def code128(chaine=None): """ Calcule le Code128 pour les codes à barres print code128('ABC') #ÃŒABC!ÃŽ print code128('123') #ÃŒ123(ÃŽ print code128('BA757') #ÃŒBA757\ÃŽ print code128('Bonjour') #ÃŒBonjourGÃŽ print code128('XLP5289741') #ÃŒXLPÇTyjÈ1bÃŽ print code128('3754 KC 75') #??EVÈ KC 75)ÃŽ """ if chaine is None: chaine=u1252(GlobalPARAM[0]) else: chaine=u1252(chaine) def testnum(chaine): for i in chaine: if not i in string.digits: return False return True Code128='' tableB=True i=0 while i103: checksum-=103 if checksum<95: checksum+=32 else: checksum+=100 Code128=Code128+chr(checksum)+chr(206) return Code128 #*** MODIF *** 31.5.05 : ajout clipboard si fichier vide + gestion du 'SHOW' def trtimage(filein="C:\\Ponx\\Exemples\\ga2.jpg", fileout="C:\\Temp.jpg", lstrt=[] ): global GlobalPARAM,chaineretour import Image,ImageGrab if filein=='': img=ImageGrab.grabclipboard() #img.show() else: img=Image.open(filein) #if not isinstance(im, Image.Image): # return for trt in lstrt: #msginfo("trt",trt) if trt[:7]=='RESIZE=': resize = string.atoi(trt[7:]) if resize != 100 : x,y = img.size x = x*resize//100 y = y*resize//100 nouvelletaille = (x,y) img = img.resize(nouvelletaille) elif trt[:7]=='ROTATE=': rotate = string.atoi(trt[7:]) if rotate != 0: img = img.rotate(rotate) elif trt[:5]=='FLIP=': flip = trt[5:] if flip == 'HORIZONTAL': img = img.transpose(Image.FLIP_LEFT_RIGHT) if flip == 'VERTICAL': img = img.transpose(Image.FLIP_TOP_BOTTOM) elif trt[:5]=='CROP=': postai=string.split(trt[5:],',') try: img = img.crop((int(postai[0]),int(postai[1]),int(postai[2]),int(postai[3]))) #img = img.crop((50,50,100,100)) except: pass elif trt[:4]=='SHOW': img.show() elif trt[:7]=='@SCRIPT': cmde=GlobalPARAM[0] try: item = u1252(cmde).replace('\r\n', '\n') exec(item,globals(),globals()) except: pass x,y = img.size chaineretour=str(x)+"|"+str(y) img.save(fileout) return(x,y) #*** NEW 3.203 ; 16.04.06 *** def genimagetexture(largeur=400,hauteur=200, mode='RGB',ftexture='C:\\text\\wood004.jpg',fichier='C:\\image.jpg'): """ Génère une image texturée (tramée). Paramètres : @largeur @hauteur @mode 'RGB' (24 bits) ou 'L' (8 bits) ou '1' (1 bit) @ftexturee nom du fichier de texture @fichier nom du fichier en sortie Exemples : genimagetexture(600, 300, 'RGB', 'C:\\text\\wood004.jpg', 'C:\\toto.bmp') genimagetexture(600, 300, 'L', 'C:\\text\\tissu3.jpg', 'C:\\toto.jpg') """ import Image, ImageDraw img=Image.new(mode,(largeur,hauteur)) tampon = Image.open(ftexture) #print tampon.size tlarg=tampon.size[0] thaut=tampon.size[1] for y in range(0,hauteur,thaut): for x in range(0,largeur,tlarg): img.paste(tampon,(x,y)) if fichier!='' and not(fichier is None): img.save(fichier) else: img.show() #*** NEW *** def tpq_second(): """Gestion des taches parallèles """ typ,task=tqp2_taskwait.get() tqp_taskcours.put(task) #print typ,tqp2_taskwait.qsize(),'<=====' if typ=='END': tqp_taskcours.get() tqp_result.put(None) else: #print"Normal" tqp_result.put(eval(task,globals(),globals())) tqp_taskcours.get() #*** NEW *** def tpq_principal(): """Gestion des taches séquentielles """ while(1): typ,task=tqp_taskwait.get() tqp_taskcours.put(task) #print typ,tqp_taskwait.qsize(),'<=====' if typ=='END': tqp_taskcours.get() tqp_result.put(None) break else: #wprint"Normal" tqp_result.put(eval(task,globals(),globals())) tqp_taskcours.get() #*** NEW *** def taskdef(typ,task): """Permet de définir une tache dans le système multithreading simplifié de Ponx @param typ: soit 'PARA' pour une execution immédiate, en multi-taches ; soit 'TASK', pour une utilisation séquentielle, via Queue """ global tqp_2 if len(ponx_thread)==0: taskinit() #msginfo("Task","initialisé") if typ=='PARA': tqp_2=tqp_2+1 ponx_thread.append(threading.Thread(target=tpq_second)) ponx_thread[tqp_2].setDaemon(True) ponx_thread[tqp_2].start() tqp2_taskwait.put((typ,task)) else: tqp_taskwait.put((typ,task)) #*** NEW *** def taskwaitnext(): """ Retourne le resultat de la tache terminée suivante attend, si nécessaire. S'il n'y a ni résultats en attente, ni taches non terminées, retourne None """ if tqp_result.qsize()>0: return tqp_result.get() elif tqp_taskwait.qsize()+tqp_taskcours.qsize()>0: return tqp_result.get() #*** NEW *** def tasknowaitnext(): """ Retourne le resultat de la tache terminée suivante attend, si nécessaire. S'il n'y a ni résultats en attente, ni taches non terminées, retourne None """ if tqp_result.qsize()>0: return tqp_result.get() else: return None #*** NEW *** def taskwaitnb(): """ Retourne le nb de résultats en attente s'il n'y en a pas, retourne - (moins) le nb de taches non terminées) """ nb=tqp_result.qsize() if nb>0: return nb else: nb=-tqp_taskwait.qsize()-tqp_taskcours.qsize() if nb<0: return nb+1 else: return nb #*** NEW *** def tasknlnb(): """ Retourne le nb de taches 'non lancées' en attente (restant à lancer) """ return(tqp_taskwait.qsize()) #*** NEW *** def taskcoursnb(): """ Retourne le nb de taches 'en cours' non terminées (résultats en attente) """ return(tqp_taskcours.qsize()) #*** NEW *** def taskinit(): """ Initialise le système multithreading simplifié de Ponx. """ ponx_thread.append(threading.Thread(target=tpq_principal,name="principal")) ponx_thread[tqp_2].setDaemon(True) ponx_thread[tqp_2].start() """ Principe général du système multithreading simplifié de Ponx. Les taches sont définies (envoyées) dans une file d'exécution. Les résultats sont enregistrés dans une autre file. Ils peuvent donc être récupérés ultérieurement. En envoie une tache, puis on l'oublie, jusqu'au moment où l'on a besoin du résultat. Il y a deux modes d'exécution des taches : séquentiel, ou parallèle. Une tache séquentielle n'est démarrée que lorsque la précédente est terminée. Les taches parallèles s'exécutent simultanément. Mais les deux travaillent en arrière-plan (la main est rendue immédiatement). Les deux possibilités coexistent, mais ne sont pas intégrées l'une avec l'autre. Autrement dit, on ne peut pas gérer parallèlement des listes de taches séquentielles. Si vous avez besoin de ce genre de choses, programmez-les directement en Python. Ponx suivra. Une tache, c'est une ligne d'instruction(s). En cas de besoin, il est possible de définir une, ou des, fonctions intermédiaires. A la fin de PONX, les taches en cours sont abandonnées. Le multi-threading "daemoning" n'est pas supporté par Windows. Mais la fin de PONX, ce n'est pas le ".close()" d'Object-Pal, ou la fermeture d'une fiche. C'est la sortie de Paradox. Il est donc tout à fait possible de lancer des taches, depuis une fiche Paradox, puis de fermer cette fiche, sans que cela impacte les taches. Il n'y a aucun moyen d'arrêter une tache en cours (sauf à arrêter Ponx). Attention, donc, aux taches infinies (taches qui bouclent indéfiniment, erreur d'attente de périphérique, ou attente invisible d'utilisateur, etc.) Il existe des fonctions qui indiquent combien il y a de taches en attente, en cours, combien de résultats sont en attente. Une autre fonction met PONX en attente (bloquante) du résultat suivant. Conseils : Les taches sont indépendantes, et n'ont pas de moyens de communications entres elles. Le système étant incapable de déterminer si les taches sont "thread-safe", il appartient au développeur de gérer cela. Néanmoins, les taches séquentielles permettent de contourner partiellement le problème des taches non "thread-safe". Il suffit de ne pas utiliser appeler les fonctions concernées, en dehors du système multithreading simplifié de Ponx. Par exemple, la lecture d'e-mails n'est pas "thread-safe". Mais, on peut très bien demander la récupération des e-mails successifs, dans autant de taches séquentielles. Il sera possible de faire autre chose pendant que les e-mails arriveront. Attention, aussi, à l'utilisation du système multithreading simplifié avec iPONX. Tant que l'on reste en arrière-plan, pas de problème. Mais la mise à jour par des threads des UIobjects, simultanément au travail de l'utilisateur, ou du programme iPONX principal peut entraîner des plantages. Cela est dû au fait que ni javascript, ni les pages HTML ne sont "thread-safes". Des tests poussés (travail intensif de saisie/déclenchement de scripts de validation, et de threads modifiant simultanément des UIobjects m'on donné un plantage pour 50 modifications. A vous de jouer avec ça. Le système n'est pas actif par défaut, on l'active avec taskinit(). """ def tache(ordre, numtache=1, nomtache=None, fonction=None): global GlobalTacheID,chaineretour,GlobalCONTROL import threading if ordre=="Lance": GlobalTacheID[numtache] = threading.Thread(target=fonction,name=nomtache) #GlobalTacheID[numtache].setDaemon(1) GlobalTacheID[numtache].start() vifi(nomtache+' num.'+str(numtache)) elif ordre=="Liste": GlobalCONTROL=GlobalCONTROL+string.join(threading.enumerate(),'\t') elif ordre=="Etat": GlobalCONTROL=GlobalCONTROL+str(GlobalTacheID[numtache].isAlive())+'\t' class Singleton(object): _singleton = None def getSingleton(cls): if not isinstance(cls._singleton,cls): cls._singleton = cls() return cls._singleton getSingleton = classmethod(getSingleton) class gggg(Singleton): def affecte(self,valeur): self.data=valeur def vret(self): global chaineretour chaineretour=self.data try: #import MySQLdb pass except: pass defaultdatabase = 'test' class table: connexion = None database = None nom = None nfields = 0 structure=[] champs={} def __init__(self,nomtable='temp',database=defaultdatabase): self.database=database self.nom = nomtable #self.connexion = sqlite.connect(database) self.connexion = MySQLdb.Connect(host='localhost', db=database, user='',passwd='') def create(self,struc): cu = self.connexion.cursor() try: sq='DROP TABLE '+self.nom cu.execute(sq) self.connexion.commit() except: pass sq = 'create table '+self.nom+"(" for item in struc: sq=sq+item[0]+' '+item[1]+', ' self.nfields+=1 self.structure.append([item[0],item[1]]) self.champs[item[0]]=self.nfields sq=sq[:-2]+')' cu.execute(sq) self.connexion.commit() class tcursor: connexion = None database = None nom = None cursor = None eof=False nfields = 0 recno = 0 structure=[] champs={} buf0 =[] buf1 =[] def __init__(self,tbl, req=None): self.database=tbl.database self.nom=tbl.nom self.structure=tbl.structure self.champs=tbl.champs self.nfields=tbl.nfields self.cursor=tbl.connexion.cursor() #self.recno=self.cursor.current_recnum if req is None: req="select * from "+self.nom #print req self.cursor.execute(req) def next(self, nbrec=1): for i in xrange(nbrec): ret = self.cursor.fetchone() #self.recno=self.cursor.current_recnum self.buf0=ret self.buf1=self.buf0 if ret is None : self.eof=True return ret def skip(self, nbrec=1): return self.next(nbrec) def nextrecord(self, nbrec=1): return self.next(nbrec) def setfieldvalue(self, nfield, value): self.buf1[nfield]=value def fieldvalue(self, num): if type(num)==int: return self.buf1[num-1] if type(num)==str: return self.buf1[self.champs[num]-1] def n(self, num): return self.fieldvalue(num) def fieldname(self, nfield): return self.structure[nfield][0] def postrecord(self): sq=None def insertrecord(self,*tdata): sq="insert into "+self.nom+"(" ss='' self.buf1=[] for ch in self.structure: sq += ch[0]+', ' ss += '%s, ' self.buf1.append(None) sq=sq[:-2]+') values ('+ss[:-2]+')' if not(tdata is None): self.buf1=[] for item in tdata: self.buf1.append(item) valeurs=[] for item in self.buf1: valeurs.append(str(item)) self.buf0=self.buf1 #print sq,valeurs self.cursor.execute(sq, valeurs) tbl.connexion.commit() #self.recno=self.cursor.current_recnum def rgenerator1(ll): for i in ll: yield(i) def rgenerator2(ll): for l in ll: for i in l: yield(i) def rgeneratord(dic): for i in dic: yield(i) yield(dic[i]) #*** v3.229 def rgeneratordic(**dic): for i in dic: yield(i) yield(dic[i]) def IID_IObjectSafety(): return True #----------------------- Cherrypy ------------------------------------ def tcherry(): global cherrypy os.chdir('D:\\home\\site') try: execfile('D:\\home\\site\\pxcherry.py',globals(),globals()) #execfile('pxcherry.py',globals(),globals()) except: tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) #cherrypy.root.spage = spage() ###cherrypy.server.start() cherrypy.config.update(settings) cherrypy.tree.mount(psite()) cherrypy.server.quickstart() cherrypy.engine.start() def pcherry(): global cherrypy import cherrypy from cherrypy.lib import cptools thrcherry=threading.Thread(target=tcherry) thrcherry.setDaemon(True) thrcherry.start() #-------- Début --- partie --- spécifique --- à --- PBridge.AutoIt --------- def autoitmmopen(): global objautoitmmap import mmap objautoitmmap=mmap.mmap(0,32767,'autoitmmap') def autoitmmwrite(data): objautoitmmap.seek(0) objautoitmmap.write(data) objautoitmmap.flush() def autoitmmread(): objautoitmmap.seek(0) data=objautoitmmap.read(32767) #print 83,data[:30]+"**" return data def autoitmmclose(): global objautoitmmap objautoitmmap.close() del objautoitmmap def envoiautoitmessage(txt): global hautoitmessage if not hautoitmessage: hautoitmessage = win32gui.FindWindowEx(0,0,0,autoitprefix) #print hautoitmessage,hex(hautoitmessage) if hautoitmessage<1: autoitmmclose() return -1 else: time.sleep(0.1) autoitmmopen() #print win32gui.GetWindowText(hautoitmessage) autoitmmwrite("EMPTY:") import struct,array data = array.array( 'c', txt+chr(0)) data_ad, data_len = data.buffer_info() datastruct = array.array('c', struct.pack("IIP", data_len, data_len, data_ad)) struct_message = datastruct.buffer_info()[0] win32api.SendMessage(hautoitmessage, win32con.WM_COPYDATA, 0, struct_message) return hautoitmessage def getautoitreturn(): data=autoitmmread() if data[:7]!="RETURN:": time.sleep(0.01) data=autoitmmread() compteur=30*10 while data[:7]!="RETURN:": time.sleep(0.09) data=autoitmmread() compteur-=1 #print compteur, if compteur<0: return -1,None lendata=int(data[8:17]) return 1,data[17:lendata+17] def autoitload(chemin,fichier): global hautoitmessage hautoitmessage = win32gui.FindWindowEx(0,0,0,autoitprefix) if hautoitmessage>0: time.sleep(0.1) autoitmmopen() return hautoitmessage if not chemin.endswith('\\'): chemin+='\\' try: os.system('start "" /D'+chemin+' "'+chemin+fichier+'" ') except: return -1 n=10 while n>0: time.sleep(0.5) hautoitmessage = win32gui.FindWindowEx(0,0,0,autoitprefix) if hautoitmessage>0: time.sleep(0.1) autoitmmopen() return hautoitmessage n-=1 autoitmmclose() return -1 def autoit(ordre,*args): if ordre.startswith('NORETURN_'): flagreturn=False #ordre=ordre[9:] #commentaire version pbautoit 1.2 et + else: flagreturn=True try: chaine=u1252(ordre)+"|||" for i in args: if type(i) in (types.StringType,types.UnicodeType): chaine += u1252(i)+"|||" else: chaine += str(i)+"|||" except: return "ERROR: Argument(s) error",None if envoiautoitmessage(chaine)<0: return "ERROR: AutoIt-window not found",None test="OK" vret="" if flagreturn: test,vret=getautoitreturn() if test<0: return "ERROR AutoIt"," " else: return "OK",vret def pxautoit(ordre,*args): return autoit(ordre,*args)[1] #------------------- AutoitAutoMessage ---------------------------------------- def autoitautomessageload(chemin=GlobalPonxDir,fichier="autoitautomessage.exe",titrefenetre="(ponxautoitauto) MESSAGE",dureemax=12000): """ exemple: autoitautomessageload() envoiautoitautomessage("MESSAGE|||AAAAAAAAAAA") time.sleep(1) envoiautoitautomessage(u"CLOSE|||2000") """ global hautoitmessage,autoitprefix autoitprefix=titrefenetre hautoitmessage = win32gui.FindWindowEx(0,0,0,autoitprefix) if hautoitmessage>0: time.sleep(0.1) return hautoitmessage try: os.spawnl(os.P_NOWAIT,os.path.join(chemin,fichier),os.path.join(chemin,fichier),str(dureemax)) #os.spawnl(os.P_NOWAIT,os.path.join(chemin,fichier),"aaa","5555") except: return -1 n=10 while n>0: time.sleep(0.5) hautoitmessage = win32gui.FindWindowEx(0,0,0,autoitprefix) if hautoitmessage>0: time.sleep(0.1) return hautoitmessage n-=1 autoitmmclose() return -1 def envoiautoitautomessage(txt): """ exemple: autoitautomessageload() envoiautoitautomessage("MESSAGE|||AAAAAAAAAAA") time.sleep(1) envoiautoitautomessage(u"CLOSE|||3000") """ global hautoitmessage if not hautoitmessage: hautoitmessage = win32gui.FindWindowEx(0,0,0,autoitprefix) if hautoitmessage<1: return -1 else: time.sleep(0.1) import struct,array data = array.array( 'c', u1252(txt)+chr(0)) data_ad, data_len = data.buffer_info() datastruct = array.array('c', struct.pack("IIP", data_len, data_len, data_ad)) struct_message = datastruct.buffer_info()[0] win32api.SendMessage(hautoitmessage, win32con.WM_COPYDATA, 0, struct_message) return hautoitmessage #------------------- AutoitAutoMessage (fin)--------------------------------------- def insideprun(argu, *param): global nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalPARAM,GlobalPARAMindexRetour,GlobalPARAMUI chaineretour='' GlobalPARAMindexRetour=-1 item = u1252(argu).replace('\r\n', '\n') GlobalPARAM=param try: ccod=compile(item,'ponx:PRun','exec') flagcompile=True except: chaineretour=_("Erreur de compilation") flagcompile=False if flagcompile==True: try: exec(ccod,globals(),globals()) except: #msginfo("pb avec ponx:PRun') #msginfo("Type_erreur: ",str(sys.exc_info()[0])) #msginfo("Valeur erronnée: ",str(sys.exc_info()[1])) tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) return chaineretour def insidepret(argu, *param): global nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalPARAM,GlobalPARAMindexRetour,GlobalPARAMUI vret=None GlobalPARAMindexRetour=-1 item = u1252(argu).replace('\r\n', '\n') GlobalPARAM=param try: ccod=compile(item,'ponx:PRun','exec') flagcompile=True except: vret=_("Erreur de compilation") flagcompile=False if flagcompile==True: try: vret=eval(ccod,globals(),globals()) except: msginfo("pb avec ponxd:PRet") msginfo("Type_erreur: ",str(sys.exc_info()[0])) msginfo("Valeur erronnée: ",str(sys.exc_info()[1])) tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) return vret # new 14.02.2008 ; v3.289 def pluiefrun(dossier,fiche=None): """ Lance une fiche PLUIE, dans le répertoire (dossier) indiqué Exemple: import win32com.client pd = win32com.client.Dispatch('Ponxd.Mci') print pd.pluiefrun('D:\\Dev\\Python\\ptest','ex1val') """ global chaineretour value=pluiedir() import pluie if fiche: os.chdir(dossier) if not fiche.endswith('.utilise') and not fiche.endswith('.py'): fiche+=".utilise" vret=execfile(fiche,globals(),globals()) time.sleep(0.1) return chaineretour #********************************************************************* #*********************** Ponx **************************************** #********************************************************************* class ponx(object) : _public_methods_ = ['PRun','PRunnostop','PRet','PRet1','PCall','PRCall','PCallkw','PRCallkw','UIfilGet','UIfilPut','PRunCLIP', 'PxR','PxE','PxE0','PxRUI','PxEUI','PxEL','PxELL','PxRL','PxRLall','PxRGenerator1','PxRGenerator2','PxRGeneratordic', 'PRunf', 'TabletW','TabletSelect','TabletR','TabletRP','TabletRPnext', 'PxELdispatch', 'simpledispatch', 'PxUIdispatch', 'PCtrl', 'PRun1Brut', 'PVersion', 'Ptest', 'getvpublic', 'mv0', 'mv1', 'mva', 'cherryread','cherryzeroread','cherrytemplate','cherrywrite','cherrysession','cherrycontentE','cherrycontentR', ] _public_attrs_ = ['signal','flag','version','obj'] _readonly_attrs_ = ['version'] _reg_progid_ = "Ponx.Mci" _reg_clsid_ = "{EC501258-201C-449C-BE20-837A316EA382}" _reg_desc_ = 'Ponx - serveur de fonctionnalites' from win32com.axscript import axscript _com_interfaces_ = [axscript.IID_IObjectSafety] #*** 15.08.05 v2.37 ; introduction des propriétés *** signal = "Ponx_None" flag = False version = GlobalPVersion obj=None def __init__(self): """ lancé au démarrage de Ponx """ value=ponxdir() if not sys.path.__contains__(value): sys.path.append(value) #msginfo('instanciation','Ponx') def __del__(self): """ lancé en sortie ou fermeture de Ponx """ #msginfo('del','Ponx') pass def _CreateInstance_(self, clsid, reqIID): return pythoncom.WrapObject(self, reqIID) #***MODIF: 14.6.5 gestion erreur*** #***MODIF: 20.6.5 v2.31 passage deparamètres plus rapide*** def PRun(self, argu, *param): global nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalPARAM,GlobalPARAMindexRetour,GlobalPARAMUI,vpublic chaineretour='' GlobalPARAMindexRetour=-1 item = argu.replace(u'\r','') #item = uutf8(argu).replace('\r\n', '\n') GlobalPARAM=param try: ccod=compile(item,'ponx:PRun','exec') flagcompile=True except: chaineretour=_("Erreur de compilation") flagcompile=False if flagcompile==True: try: exec(ccod,globals(),globals()) except: #msginfo("pb avec ponx:PRun") #msginfo("Type_erreur: ",str(sys.exc_info()[0])) #msginfo("Valeur erronnée: ",str(sys.exc_info()[1])) tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) return chaineretour def PRunnostop(self, argu, *param): global nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalPARAM,GlobalPARAMindexRetour,GlobalPARAMUI,vpublic chaineretour='' try: GlobalPARAMindexRetour=-1 item = argu.replace(u'\r','') GlobalPARAM=param except: pass try: ccod=compile(item,'ponx:PRun','exec') flagcompile=True except: chaineretour=_("Erreur de compilation") flagcompile=False if flagcompile==True: try: exec(ccod,globals(),globals()) except: #msginfo("pb avec ponx:PRun') #msginfo("Type_erreur: ",str(sys.exc_info()[0])) #msginfo("Valeur erronnée: ",str(sys.exc_info()[1])) ###tb=sys.exc_info()[2] #traceback ###msginfo(str(sys.exc_info()[0]),traceback.format_exc()) pass return chaineretour #*** Modif 3.6.05 v2.30 passage des paramètres complémentaires*** def PRet(self, argu, *param): global GlobalPARAM,GlobalPARAMindexRetour,vpublic GlobalPARAMindexRetour=-1 item = argu.replace(u'\r','') if param: GlobalPARAM=param try: ccod=compile(item,'ponx:PRet','eval') flagcompile=True except: flagcompile=False if flagcompile==True: return eval(ccod,globals(),globals()) #return eval(ccod) #GlobalPARAM=param #GlobalPARAMindexRetour=-1 #return eval(argu,globals(),globals()) #***NEW/MODIF*** def PRet1(self, argu, param): """applique argu à param, et retourne la valeur""" global GlobalPARAM,vpublic if param: GlobalPARAM=param if argu[-1]==')' and argu[0]!='.': s=string.replace(argu,"xchaine","GlobalPARAM") sexec="""global chaineretour,GlobalPARAM\nchaineretour="""+s else: sexec="""global chaineretour,GlobalPARAM\nchaineretour=GlobalPARAM"""+argu ccod=compile(sexec,'ponx:PRet1','exec') exec(ccod,globals(),globals()) return chaineretour #*** Modif 3.12 def PCall(self, argu, *param): global GlobalPARAM,GlobalPARAMindexRetour,chaineretour chaineretour='' GlobalPARAMindexRetour=-1 item = "fonction="+argu.replace(u'\r','') GlobalPARAM=[] if param: for par in param: GlobalPARAM.append(par.replace(u'\r','')) #msginfo("item",item) try: ccod=compile(item,'ponx:PCallkw','exec') flagcompile=True except: flagcompile=False if flagcompile==True: exec(ccod,globals(),globals()) #msginfo(str(len(GlobalPARAM)),str(GlobalPARAM)) apply(fonction,GlobalPARAM) return chaineretour #*** 3.12 def PCallkw(self, argu, *param): global GlobalPARAM,GlobalPARAMindexRetour,chaineretour chaineretour='' GlobalPARAMindexRetour=-1 item = argu.replace(u'\r','') GlobalPARAM=[] if param: for par in param: GlobalPARAM.append(par.replace(u'\r','')) item=item+"("+(",".join(GlobalPARAM))+")" #msginfo("item",item) try: ccod=compile(item,'ponx:PCallkw','exec') flagcompile=True except: flagcompile=False if flagcompile==True: exec(ccod,globals(),globals()) return chaineretour #*** 3.12 def PRCall(self, argu, *param): global GlobalPARAM,GlobalPARAMindexRetour GlobalPARAMindexRetour=-1 item = "fonction="+argu.replace(u'\r','') GlobalPARAM=[] if param: for par in param: GlobalPARAM.append(par.replace(u'\r','')) #msginfo("item",item) try: ccod=compile(item,'ponx:PRCall','exec') flagcompile=True except: flagcompile=False if flagcompile==True: exec(ccod,globals(),globals()) #msginfo(str(len(GlobalPARAM)),str(GlobalPARAM)) return(apply(fonction,GlobalPARAM)) #*** 3.12 def PRCallkw(self, argu, *param): global GlobalPARAM,GlobalPARAMindexRetour GlobalPARAMindexRetour=-1 item = argu.replace(u'\r','') GlobalPARAM=[] if param: for par in param: GlobalPARAM.append(par.replace(u'\r','')) item=item+"("+(",".join(GlobalPARAM))+")" #msginfo("item",item) try: ccod=compile(item,'ponx:PRCallkw','eval') flagcompile=True except: flagcompile=False if flagcompile==True: return eval(ccod,globals(),globals()) #***NEW*** def UIfilGet(self): if len(UIfil)>0: return UIfil.pop(0) else: return None #***NEW*** def UIfilPut(self, *argu): for item in argu: msginfo("a",item) UIfil.put(item) #***MODIF: nom du fichier*** def PRunCLIP(self): global nfichier,fichier,vifi,ponxopen,ponxquit,chaineretour,GlobalPARAM,GlobalPARAMindexRetour chaineretour='' GlobalPARAM=[] GlobalPARAMindexRetour=-1 win32clipboard.OpenClipboard() clpdata=win32clipboard.GetClipboardData(win32con.CF_TEXT) win32clipboard.CloseClipboard() item = re.sub(u'\r','', str(clpdata)) #item = re.sub('\r\n', '\n', clpdata.encode(CodingParDefaut,'replace')) #item = str(clpdata) #chaineretour=item #exec(item) ccod=compile(item,'ponx:PRunCLIP','exec') exec(ccod,globals(),globals()) GlobalPARAMindexRetour=-1 return chaineretour def PxR(self, num=None): global GlobalPARAM,GlobalPARAMindexRetour if num is None: GlobalPARAMindexRetour+=1 else: GlobalPARAMindexRetour=num #msginfo(str(GlobalPARAMindexRetour),GlobalPARAM[0]) if GlobalPARAMindexRetour0: if args[0]==u'___dict___': setattr(vpublic,name,{}) self.listdict[name]=getattr(vpublic,name) return True clef=None if name.find("___")>-1: try: #name=name.replace('___','.') name,clef=name.split(u'___') except: pass if name.find(u'°')>-1: try: #name=name.replace(chr(176),'.') # le ° 'numéro' name,clef=name.split(u'°') except: pass #msginfo('7755',str(clef)) if not clef: if name in self.listdict: #msginfo("7757",str(wFlags)+" "+str(args)) if wFlags & pythoncom.DISPATCH_PROPERTYGET: #msginfo("wFlags",str(wFlags)) if wFlags!=3: raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) else: pass #return #utile pour VBScript ? elif wFlags==1: pass #raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) if wFlags==1 or wFlags==3: """ Retourne une entrée de dictionnaire demandée comme une fonction """ if len(args)>0: clef=args[0] d = self.listdict[name] if len(args)>1: d[args[0][0]]=args[0][1] return else: vret=d[clef] return(vret,) #msginfo('name-',name+' '+str(len(args))) #print 7762,wFlags,name,args if len(args)<1: """ Retourne la valeur d'une propriété / variable de Ponx (global) """ #if name in self.listdict: if clef: return(self.listdict[name][clef],) #d = self.listdict[name] #vret=d[clef] else: return(getattr(vpublic,name),) #vret = getattr(vpublic,name) #return(vret,) #if type(vret) in (types.TupleType,): # return(vret,) #else: # return(vret) else: """ Affecte une variable (global) de Ponx """ #msginfo("8794",str(hasattr(vpublic,name))) if name in self.listdict: if clef: if type(args[0]) in (types.TupleType,): self.listdict[name][clef]=list(args[0]) else: self.listdict[name][clef]=args[0] return #d = self.listdict[name] #d[clef]=args[0] #return else: d = self.listdict[name] if type(args[0][1]) in (types.TupleType,): d[args[0][0]]=list(args[0][1]) else: d[args[0][0]]=args[0][1] return else: if type(args[0]) in (types.TupleType,): setattr(vpublic,name,list(args[0])) else: setattr(vpublic,name,args[0]) return # --------------------------- Ponx Dynamic --------------------------- class ponxd(object) : _public_methods_ = ['_dynamic_','dtest'] _public_attrs_ = ['signal','propriete','flagd','version','pdarray'] _readonly_attrs_ = ['version'] _reg_progid_ = "Ponxd.Mci" _reg_policy_spec_ = "DynamicPolicy" _reg_clsid_ = "{F0A573A9-10E8-4CD4-94F1-09A669C0D287}" _reg_desc_ = 'Ponx - version dynamique' _MethodDescriptorType = type(list.append) #*** 01.11.05 v2.99 *** signal = "Ponx_dynamic_None" propriete='ABC' flagd = 1234.56 pdarray=[11,22,33,44,55,66,77,88,99,00] dyntotal={} dobj={} #pobj={} #dbuild={} def dtest(self): l=[11,22,3333] return(l,) obj=globals() for i in obj: dobj[i]=obj[i] dobj[i.upper()]=obj[i] dobj['ponx.'+i]=obj[i] dobj['PONX.'+i.upper()]=obj[i] obj=None import __builtin__ for i in dir(__builtin__): ##dbuild[i.upper()]=__builtin__.__dict__[i] #même résultat que ligne ci-dessous. dobj[i]=getattr(__builtin__, i) dobj[i.upper()]=getattr(__builtin__, i) temp=getattr(__builtin__, i) dobj['builtin.'+i]=temp dobj['BUILTIN.'+i.upper()]=temp if type(dobj['builtin.'+i]) in (types.TypeType,types.ClassType): for sousi in dir(dobj['builtin.'+i]): if sousi != "__abstractmethods__": temp=getattr(dobj['builtin.'+i],sousi) dobj['builtin.'+i+'.'+sousi]=temp dobj[('builtin.'+i+'.'+sousi).upper()]=temp #print ('builtin.'+i+'.'+sousi).upper(), type(dobj['builtin.'+i+'.'+sousi]) def __init__(self): def _pxchargem(modul): for i in dir(modul): #msginfo(str(modul)) self.dobj[modul.__name__+'.'+i]=getattr(modul, i) self.dobj[modul.__name__.upper()+'.'+i.upper()]=getattr(modul, i) #ponx (globals()) #__builtin__ _pxchargem(os) _pxchargem(os.path) _pxchargem(sys) _pxchargem(string) _pxchargem(cStringIO) _pxchargem(cPickle) _pxchargem(re) _pxchargem(time) _pxchargem(datetime) _pxchargem(quopri) _pxchargem(zipfile) _pxchargem(zlib) _pxchargem(binascii) _pxchargem(codecs) _pxchargem(threading) _pxchargem(Queue) #_pxchargem(wscr) pglobal.GlobalPARAMliste=GlobalPARAMliste value=ponxdir() if not sys.path.__contains__(value): sys.path.append(value) def _CreateInstance_(self, clsid, reqIID): return pythoncom.WrapObject(self, reqIID) def _dynamic_(self, name, lcid, wFlags, args): global GlobalObject #name=name.encode('utf-8','replace') """ print "name",name print "lcid",lcid print "wFlags",wFlags print "pythoncom.DISPATCH_METHOD",pythoncom.DISPATCH_METHOD print "pythoncom.DISPATCH_PROPERTYGET",pythoncom.DISPATCH_PROPERTYGET print "pythoncom.DISPATCH_PROPERTYPUT",pythoncom.DISPATCH_PROPERTYPUT print "pythoncom.DISPATCH_PROPERTYPUTREF",pythoncom.DISPATCH_PROPERTYPUTREF print "pythoncom.DISPID_UNKNOWN",pythoncom.DISPID_UNKNOWN print "pythoncom.DISPID_VALUE",pythoncom.DISPID_VALUE print "pythoncom.DISPID_PROPERTYPUT",pythoncom.DISPID_PROPERTYPUT print "pythoncom.DISPID_NEWENUM",pythoncom.DISPID_NEWENUM print "pythoncom.DISPID_EVALUATE",pythoncom.DISPID_EVALUATE print "pythoncom.DISPID_CONSTRUCTOR",pythoncom.DISPID_CONSTRUCTOR print "pythoncom.DISPID_DESTRUCTOR",pythoncom.DISPID_DESTRUCTOR print "pythoncom.DISPID_COLLECT",pythoncom.DISPID_COLLECT print "pythoncom.DISPID_STARTENUM",pythoncom.DISPID_STARTENUM print type(args),str(args) """ #if wFlags & pythoncom.DISPATCH_PROPERTYGET: # raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) """ msginfo("---"," ") msginfo("name",name) msginfo("lcid",str(lcid)) msginfo("args",str(args)) msginfo("wFlags",str(wFlags)+" "+str(pythoncom.DISPATCH_PROPERTYGET)) """ try: name=name.replace(u'___',u'.') except: pass try: name=name.replace(u'°',u'.') # le ° 'numéro' except: pass #msginfo('name-',name) if name=="PXCHARGE" or name=="pxcharge": if wFlags & pythoncom.DISPATCH_PROPERTYGET: raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) aargs=str(args[0]) sret=None try: ccod=compile(aargs, 'ponx:Pdynamic', 'exec') flagcompile=True except: sret=_("Erreur de compilation") flagcompile=False if flagcompile==True: try: exec(ccod,globals(),globals()) except: tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) for i in dir(GlobalObject): #msginfo("7299",str(getattr(GlobalObject, i))) self.dobj[i]=getattr(GlobalObject, i) self.dobj[i.upper()]=getattr(GlobalObject, i) return sret if name=="PXCHARGEM" or name=="pxchargem": """ #à revoir (OK pour paradox, pas pour AutoIt) if wFlags & pythoncom.DISPATCH_PROPERTYGET: msginfo('7997','OK') raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) """ #aargs=u1252(args).replace('\r\n', '\n') aargs=str(args[0]) aargs=aargs.replace('\r\n', '\n') aargs=aargs.replace('\r', '') #msginfo("aargs",aargs) #print "aargs",aargs sret=None #aargs='import pxword; GlobalObject=pxword.word()' try: ccod=compile(aargs, 'ponx:Pdynamic', 'exec') flagcompile=True except: sret=_("Erreur de compilation") flagcompile=False #str(flagcompil)) if flagcompile==True: try: exec(ccod,globals(),globals()) except: #msginfo("pb avec ponx:PRun') #msginfo("Type_erreur: ",str(sys.exc_info()[0])) #msginfo("Valeur erronnée: ",str(sys.exc_info()[1])) tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) #self.dobj={} import types if type(GlobalObject) is types.ModuleType: self.dobj[GlobalObject.__name__]=GlobalObject self.dobj[GlobalObject.__name__.upper()]=GlobalObject else: self.dobj[GlobalObject.__class__.__name__]=GlobalObject self.dobj[GlobalObject.__class__.__name__.upper()]=GlobalObject for i in dir(GlobalObject): if type(GlobalObject) is types.ModuleType: self.dobj[GlobalObject.__name__+'.'+i]=getattr(GlobalObject, i) self.dobj[GlobalObject.__name__.upper()+'.'+i.upper()]=getattr(GlobalObject, i) else: self.dobj[GlobalObject.__class__.__name__+'.'+i]=getattr(GlobalObject, i) self.dobj[GlobalObject.__class__.__name__.upper()+'.'+i.upper()]=getattr(GlobalObject, i) #print self.dobj #print len(self.dobj) #print self.dobj[GlobalObject.__class__.__name__+'.version'],GlobalObject.__class__.__name__+'.version' return sret if name=="PXCLASS" or name=="pxclass": """ chargement d'une instance d'une classe. Exemple : rb=ax('rubyscript') """ #msginfo(str(pythoncom.DISPATCH_PROPERTYGET),str(wFlags)) """ if wFlags & pythoncom.DISPATCH_PROPERTYGET: #print 'zzzz' raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) """ #aargs==u1252(args).replace('\r\n', '\n') aargs=str(args[0]) aargs=aargs.replace('\r\n', '\n') aargs=aargs.replace('\r', '') clef=aargs.split('=')[0] #msginfo("aargs",aargs) #msginfo("clef",clef) #msginfo("args[1]",args[1]) #msginfo("compile",'GlobalObject='+args[0]) #print "aargs",aargs GlobalObject=None sret=None try: ccod=compile('global GlobalObject; GlobalObject='+args[0], 'ponx:Pdynamic', 'exec') flagcompile=True except: sret=_("Erreur de compilation") flagcompile=False if flagcompile==True: try: exec(ccod,globals(),globals()) except: #msginfo("pb avec ponx:PRun') #msginfo("Type_erreur: ",str(sys.exc_info()[0])) #msginfo("Valeur erronnée: ",str(sys.exc_info()[1])) tb=sys.exc_info()[2] #traceback msginfo(str(sys.exc_info()[0]),traceback.format_exc()) ##self.dobj[GlobalObject.__class__.__name__]=GlobalObject ##self.dobj[GlobalObject.__class__.__name__.upper()]=GlobalObject self.dobj[clef]=GlobalObject self.dobj[clef.upper()]=GlobalObject #print "dobj -->",GlobalObject.__class__.__name__ #msginfo("GlobalObject.__class__.__name__",GlobalObject.__class__.__name__) for i in dir(GlobalObject): #msginfo('i',i) if i!='win32com': ##self.dobj[GlobalObject.__class__.__name__+'.'+i]=getattr(GlobalObject, i) ##self.dobj[GlobalObject.__class__.__name__.upper()+'.'+i.upper()]=getattr(GlobalObject, i) self.dobj[clef+'.'+i]=getattr(GlobalObject, i) self.dobj[clef.upper()+'.'+i.upper()]=getattr(GlobalObject, i) #print "dobj -->",GlobalObject.__class__.__name__+'.'+i #print self.dobj #msginfo("self.dobj[GlobalObject].dir",str(dir(self.dobj[GlobalObject]))) return sret if name=="PXDELETE" or name=="pxdelete": import types if wFlags & pythoncom.DISPATCH_PROPERTYGET: raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) aargs=str(args[0]) aargs=aargs.replace(u'\r', u'') #msginfo("aargs",aargs) #print "aargs",aargs sret=None GlobalObject=None adel=[] for i in self.dobj: j=i.find('.') if j>-1: if i[:j].upper()==aargs: adel.append(i) else: if i.upper()==aargs: adel.append(i) for i in adel: del self.dobj[i] del adel if name=='PXDIRECTPROPERTYGET' or name=='pxdirectpropertyget': """ Retourne la valeur d'une propriété d'un objet d'une instance de ponxd (voir P3word.fsl) """ item=False vret = eval("self.dobj['"+str(args[0])+"']."+str(args[1])) return vret if name=='PXDIRECTPROPERTYSET' or name=='pxdirectpropertyset': """ Affecte une propriété d'un objet d'une instance de ponxd (voir P3word.fsl) """ item=False exec("self.dobj['"+str(args[0])+"']."+str(args[1])+"="+str(args[2])) #print'--------------->',name try: item=self.dobj[name] #msginfo("dobj",name) except: try: item=getattr(self, string.lower(name)) #msginfo("self",name) except: item=None #msginfo("object","None") #print "item:",str(item),name if item: import types #print "item True:",str(item),name #print "------------------------item True:" #print name,str(type(item)) #msginfo("NAme",name) #msginfo("wFlags",str(wFlags)) #msginfo("pythoncom.DISPATCH_PROPERTYGET",str(pythoncom.DISPATCH_PROPERTYGET)) #msginfo("pythoncom.DISPATCH_METHOD",str(pythoncom.DISPATCH_METHOD)) if wFlags & pythoncom.DISPATCH_PROPERTYGET: #msginfo("item-type",str(type(item))) if type(item) in (types.ModuleType, types.BuiltinFunctionType, types.BuiltinMethodType, types.ClassType, types.MethodType, types.GeneratorType, types.FunctionType, self._MethodDescriptorType): #print "pre-fonction/classe",str(item) #msginfo("pre-fonction/classe",str(item)) if wFlags!=3: raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) else: pass #VBscript + wFlags=3 + méthode else: #print "pre-non_fonction/classe",str(item) #msginfo("pre-non_fonction/classe",str(item)) return item pass else: #print "item None:",str(item),name #print "=================================" #print str(self.dobj.has_key(name)) #print "=================================" pass if item: aargs=[] #msginfo("args",str(args)) for i in args: try: aargs.append(i.replace(u'\r', u'')) except: try: aargs.append(i) except: aargs.append(i) #msginfo("wFlags-2",str(wFlags)) #msginfo("name",name) #msginfo("aargs",str(aargs)) #msginfo(str(type(item)),str(type(item))) if (wFlags & pythoncom.DISPATCH_METHOD): #msginfo("callable",item.__name__) #msginfo("*aargs",str(aargs)) #msginfo("DISPATCH_METHOD",str(type(item(*aargs)))) if str(type(item))=="": #vret=self.dobj['wscr'].test() #vret=self.dobj['wscr.test'](*aargs) vret=item(*aargs) elif type(item) in (types.GeneratorType,): #gestion d'un generator (next) ; voir Ponx-generator-test.py try: vret=item.next() except: raise COMException("Generator terminé (StopIteration)", winerror.ERROR_NO_MORE_ITEMS) else: vret=item(*aargs) return(vret,) elif wFlags & pythoncom.DISPATCH_PROPERTYGET: return(item,) else: COMException("You can not set this attribute", winerror.DISP_E_BADVARTYPE) else: COMException("incorrect attribute", winerror.DISP_E_BADVARTYPE) def recordpfunc(self, fonc, prefix='ponx.'): """ Enregistrement d'une 'nouvelle' fonction (temporaire) Ponx. La fonction doit déjà exister (enregistrement seul, dans ponxDynamic """ #msginfo("fonc",fonc) self.dobj[fonc]=globals()[fonc] self.dobj[fonc.upper()]=globals()[fonc] self.dobj[prefix+fonc]=globals()[fonc] self.dobj[prefix.upper()+fonc.upper()]=globals()[fonc] def recorddefpfunc(self, source, fonc, prefix='ponx.'): """ Enregistrement d'une 'nouvelle' fonction (temporaire) Ponx. A partir du code-source fourni. """ #msginfo("fonc",fonc) insideprun(source) self.dobj[fonc]=globals()[fonc] self.dobj[fonc.upper()]=globals()[fonc] self.dobj[prefix+fonc]=globals()[fonc] self.dobj[prefix.upper()+fonc.upper()]=globals()[fonc] def propsetprun(self, name, source, prefix='ponx'): """ Affectation d'une propriété d'une instance de ponxD au resultat d'exécution d'un code-source. """ tempobj=insideprun("chaineretour="+source) self.dobj[name]=tempobj self.dobj[name.upper()]=tempobj self.dobj[prefix+name]=tempobj self.dobj[prefix.upper()+name.upper()]=tempobj self.__setattr__(name, tempobj) def recordpfunclass(self, fonc, klass='ponx'): """ Enregistrement d'une 'nouvelle' classe (temporaire) Ponx. la classe soit déjà exister. """ #msginfo("fonc",fonc) self.dobj[klass+'.'+fonc]=eval('self.dobj[klass].'+fonc) self.dobj[(klass+'.'+fonc).upper()]=eval('self.dobj[klass].'+fonc) def propaffect(self, name, args): """ Affectation d'une propriété d'une instance de ponxD """ aargs=[] try: aargs=args.replace(u'\r','') except: aargs=args self.__setattr__(name, aargs) #àcf : setattr(self,name,aargs) def pxpropertyget(self, name): """ Retourne la valeur d'une propriété d'une instance de ponxd """ msginfop("name",name) vret = self.__getattr__(name) return vret def visutest(self): global GlobalPARAMliste import pxexcel x=pxexcel.exl() x.newSheet() x.visible() GlobalPARAMliste[:]=[] GlobalPARAMliste.append([11,1111],[22,2222],[33,3333],[44,4444]) msginfo("test", str(GlobalPARAMliste)) x.setGlobalLRange(8,4) def wtest(self): pass """ # --------------------------- Ponx Dynamic --------------------------- class ponxf(object) : _public_methods_ = ['_dynamic_'] _public_attrs_ = ['version'] _readonly_attrs_ = ['version'] _reg_progid_ = "Ponxf.Mci" _reg_policy_spec_ = "DynamicPolicy" _reg_clsid_ = "{80B0A4EB-BD75-4099-84A1-A26FBCFCE9DE}" _reg_desc_ = 'Ponx - Fonction dynamique' _MethodDescriptorType = type(list.append) version = GlobalPVersion def __init__(self): value=ponxdir() self.buffer=None self.f=None if not sys.path.__contains__(value): sys.path.append(value) def _CreateInstance_(self, clsid, reqIID): return pythoncom.WrapObject(self, reqIID) def _dynamic_(self, name, lcid, wFlags, args): if wFlags & pythoncom.DISPATCH_PROPERTYGET: if wFlags!=3: raise COMException("inexistant", winerror.DISP_E_MEMBERNOTFOUND) try: name=name.replace(u'___',u'.') except: pass if self.buffer != name: if name.find('.')>-1: self.f=eval(name) else: self.f=globals()[name] self.buffer = name return self.f(*args) #return apply(self.f,args) """ if __name__=='__main__': if len(sys.argv)>1: if sys.argv[1].upper()=="VERSION": print "\r\n"+_("Ce fichier est celui de Ponx, version"),GlobalPVersion,"\r\n" time.sleep(2) if sys.argv[1].upper()=="--UNREGISTER": print _("désinscription des serveurs COM Ponx.Mci Ponxd.Mci Ponxv.Mci Ponxfd.Mci ") import win32com.server.register win32com.server.register.UseCommandLine(ponx) win32com.server.register.UseCommandLine(ponxd) win32com.server.register.UseCommandLine(ponxv) ###win32com.server.register.UseCommandLine(ponxf) time.sleep(2) else: if not os.path.isfile('pglobal.py'): f=open('pglobal.py','w') f.write('GlobalSource = None\r\n') f.close() print _("Enregistrement du server COM Ponx.Mci Ponxd.Mci Ponxv.Mci Ponxfd.Mci ; version ")+GlobalPVersion import win32com.server.register win32com.server.register.UseCommandLine(ponx) win32com.server.register.UseCommandLine(ponxd) win32com.server.register.UseCommandLine(ponxv) ###win32com.server.register.UseCommandLine(ponxf) #for it in os.environ: # print it,':',os.environ[it]