IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

question au sujet des threads


Sujet :

Python

  1. #1
    Candidat au Club
    Inscrit en
    Avril 2008
    Messages
    3
    Détails du profil
    Informations forums :
    Inscription : Avril 2008
    Messages : 3
    Points : 3
    Points
    3
    Par défaut question au sujet des threads
    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

  2. #2
    Membre habitué
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    119
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 119
    Points : 139
    Points
    139
    Par défaut
    Tu peux par exemple creer une fonction safeprint que tu protegeras avec, en effet, un lock, et tu pourras remplacer tes print par safeprint:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    import threading
    printlock=threading.Lock()
    def safeprint(message):
        try:
            printlock.acquire()
            print message
        finally:
            printlock.release()

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Question au sujet des crochets pour les listes
    Par LinuxUser dans le forum Prolog
    Réponses: 7
    Dernier message: 28/08/2008, 00h01
  2. Au sujet des threads
    Par neptune dans le forum Framework .NET
    Réponses: 2
    Dernier message: 30/07/2007, 10h59
  3. Questions au sujet des archives et des packages
    Par lecharcutierdelinux dans le forum Administration
    Réponses: 17
    Dernier message: 15/06/2007, 09h14
  4. Questions au sujet des activex
    Par Sonic dans le forum VB.NET
    Réponses: 1
    Dernier message: 14/04/2007, 12h32

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo