Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

multithreading - Many threads to write log file at same time in Python

I am writing a script to retrieve WMI info from many computers at the same time then write this info in a text file:

f = open("results.txt", 'w+') ## to clean the results file before the start


def filesize(asset):  
    f = open("results.txt", 'a+')  
    c = wmi.WMI(asset)  
    wql = 'SELECT FileSize,Name FROM CIM_DataFile where (Drive="D:" OR Drive="E:") and Caption like "%file%"'  
    for item in c.query(wql):  
        print >> f, item.Name.split("")[2].strip().upper(), str(item.FileSize)  




class myThread (threading.Thread):  
    def __init__(self,name):  
        threading.Thread.__init__(self)  
        self.name = name  
    def run(self):  
        pythoncom.CoInitialize ()  
        print "Starting " + self.name       
        filesize(self.name)  
        print "Exiting " + self.name  



thread1 = myThread('10.24.2.31')  
thread2 = myThread('10.24.2.32')  
thread3 = myThread('10.24.2.33')  
thread4 = myThread('10.24.2.34')  
thread1.start()  
thread2.start()  
thread3.start()  
thread4.start()

The problem is that all threads writing at the same time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply create your own locking mechanism to ensure that only one thread is ever writing to a file.

import threading
lock = threading.Lock()

def write_to_file(f, text, file_size):
    lock.acquire() # thread blocks at this line until it can obtain lock

    # in this section, only one thread can be present at a time.
    print >> f, text, file_size

    lock.release()

def filesize(asset):  
    f = open("results.txt", 'a+')  
    c = wmi.WMI(asset)  
    wql = 'SELECT FileSize,Name FROM CIM_DataFile where (Drive="D:" OR Drive="E:") and Caption like "%file%"'  
    for item in c.query(wql):  
        write_to_file(f, item.Name.split("")[2].strip().upper(), str(item.FileSize))

You may want to consider placing the lock around the entire for loop for item in c.query(wql): to allow each thread to do a larger chunk of work before releasing the lock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...