Bonjour,

Je suis actuellement en autoformation sur Python.
J'essaye de m'attaquer à la gestion des threads dans le cadre de mon boulot
(récupération d'information sur des postes XP du reseau via WMI)

La gestion des threads semble fonctionner correctement, mon seul problème, c'est que lorsque je souhaite ecrire dans un fichier texte ou bien affcher à l'ecran le resultat de ma recherche via WMI,
j'ai parfois le resultat de 2 threads sur la même ligne.


D'une part j'affiche avec print le resultat sur ma sortie std, et d'autre part dans un fichier uptime.csv.
Seulement de temps à autre j'ai le résultat suivant:


Suppression du fichier de resultat...
Debut du traitement a : Thu Jul 31 11:26:32 2008

Computername LastBootuUpTime Uptime (in Hour)
poste1 07/31/2008 03:12:06 8
poste17 07/30/2008 22:01:37 13
poste25 07/30/2008 22:01:36 13
poste33 07/30/2008 22:01:10 13
poste45 07/28/2008 21:33:38 61
poste47 07/30/2008 22:00:26 13
poste16 07/31/2008 03:11:57 poste34 07/30/2008 21:59:42 WXP0064 07/30/2008 22:02:08 13

J'ai essayé de regarder du coté de Lock mais j'avoue avoir un peu de mal :-)

exemple de code:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
 
# -*- coding:utf-8 -*-
 
from threading import Thread, Lock
from time import sleep, ctime
import Queue, time, random, pythoncom, wmi, os, re, win32com.client
 
maxthreads =  20 # maximum number of concurrent threads
loops = []
 
 
class Worker(Thread):
    def __init__(self, q):
        Thread.__init__(self)
        self.q  = q
 
    def run(self):
        all_done = 0
        log = open('C:\\uptime.csv', 'a')
        def WMIDateStringToDate(dtmDate):
            strDateTime = ""
            if (dtmDate[4] == 0):
                strDateTime = dtmDate[5] + '/'
            else:	
                strDateTime = dtmDate[4] + dtmDate[5] + '/'
            if (dtmDate[6] == 0):	
                strDateTime = strDateTime + dtmDate[7] + '/'
            else:	
                strDateTime = strDateTime + dtmDate[6] + dtmDate[7] + '/'
                strDateTime = strDateTime + dtmDate[0] + dtmDate[1] + dtmDate[2] + dtmDate[3] + " " + dtmDate[8] + dtmDate[9] + ":" + \
                dtmDate[10] + dtmDate[11] +':' + dtmDate[12] + dtmDate[13]
            return strDateTime
        while not all_done:  
            try:
                table = self.q.get(0)
                pythoncom.CoInitialize()
                host = loops[table]
                #stdout_lock = Lock()
                #stdout_lock.acquire()
                try:
                    strComputer = host
                    objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
                    objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
                    colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_OperatingSystem")
                    colItems2 = objSWbemServices.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_System")
                    for objItem in colItems:
                        log.write(host + ";" + WMIDateStringToDate(objItem.LastBootUpTime) + ";")
                        print host, WMIDateStringToDate(objItem.LastBootUpTime),
                    for objItem2 in colItems2:
                        up = int(objItem2.SystemUpTime)/60/60
                        log.write(str(up) + "\n")
                        print up
                except:
                    lPing = os.popen('ping '+ host + ' -n 1','r')
                    sLigne = lPing.read()
                    lResult = re.search('(perdus = 0)',sLigne)
                    try:
                        if ( len(lResult.groups(0)) == 1 ):
                            print "Probleme de connexion via WMI sur " + host
                    except:
                        print "Pas de réponse au ping du " + host
                finally:
                    pythoncom.CoUninitialize()
                    #stdout_lock.release() 
            except Queue.Empty:
                all_done = 1
 
 
if __name__ == "__main__":
    if os.path.exists('C:\\uptime.csv'):
        print "Suppression du fichier de resultat..."
        os.remove('C:\\uptime.csv')
    else:
        print "Le fichier de resultat n'existe pas il sera cree automatiquement..."
    print "Debut du traitement a :", time.ctime()
    start = "Debut du traitement a : " + time.ctime()
    fname = open('C:\\postes.txt', 'r')
    for line in fname:
        loops.append(line.strip('\n'))
    fname.close()
 
    q = Queue.Queue()
 
    for i in range(len(loops)):
        q.put(i)
 
    threads = []
    for i in range(maxthreads):
        t = Worker(q)
        threads.append(t)
        t.start()
 
 
    # wait for all threads to complete
 
    for t in threads:
        t.join();
 
    print "Fin du traitement a :", time.ctime()
Mon problème se situe ici:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
                  strComputer = host
                    objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
                    objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
                    colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_OperatingSystem")
                    colItems2 = objSWbemServices.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_System")
                    for objItem in colItems:
                        log.write(host + ";" + WMIDateStringToDate(objItem.LastBootUpTime) + ";")
                        print host, WMIDateStringToDate(objItem.LastBootUpTime),
                    for objItem2 in colItems2:
                        up = int(objItem2.SystemUpTime)/60/60
                        log.write(str(up) + "\n")
                        print up
                except:
                    lPing = os.popen('ping '+ host + ' -n 1','r')
                    sLigne = lPing.read()
                    lResult = re.search('(perdus = 0)',sLigne)
                    try:
                        if ( len(lResult.groups(0)) == 1 ):
                            print "Probleme de connexion via WMI sur " + host
                    except:
                        print "Pas de réponse au ping du " + host
                finally:
                    pythoncom.CoUninitialize()
                    #stdout_lock.release() 
            except Queue.Empty:
                all_done = 1