许多线程在Python中同时写日志文件

时间:2014-10-12 14:01:52

标签: python multithreading locking python-2.x

我正在编写一个脚本来同时从许多计算机中检索WMI信息,然后将这些信息写入文本文件中:

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()

问题是所有线程同时写入。

3 个答案:

答案 0 :(得分:23)

您可以简单地创建自己的锁定机制,以确保只有一个线程正在写入文件。

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))

您可能需要考虑在整个for循环for item in c.query(wql):周围放置锁,以允许每个线程在释放锁之前执行更大的工作。

答案 1 :(得分:5)

print不是线程安全的。改为使用logging模块(即):

import logging
import threading
import time


FORMAT = '[%(levelname)s] (%(threadName)-10s) %(message)s'

logging.basicConfig(level=logging.DEBUG,
                    format=FORMAT)

file_handler = logging.FileHandler('results.log')
file_handler.setFormatter(logging.Formatter(FORMAT))
logging.getLogger().addHandler(file_handler)


def worker():
    logging.info('Starting')
    time.sleep(2)
    logging.info('Exiting')


t1 = threading.Thread(target=worker)
t2 = threading.Thread(target=worker)

t1.start()
t2.start()

输出(以及results.log的内容):

[INFO] (Thread-1  ) Starting
[INFO] (Thread-2  ) Starting
[INFO] (Thread-1  ) Exiting
[INFO] (Thread-2  ) Exiting

您可以使用Thread-n关键字参数设置自己的名称,而不是使用默认名称(name),%(threadName)格式化指令随后将使用该参数:

t = threading.Thread(name="My worker thread", target=worker)

(此示例改编自Doug Hellmann's excellent article about the threading module

中的示例

答案 2 :(得分:3)

对于另一个解决方案,使用Pool计算数据,将其返回到父进程。然后,此父级将所有数据写入文件。因为一次只有一个proc写入文件,所以不需要额外的锁定。

请注意,以下内容使用进程池,而不是线程。这使得代码比使用threading模块放在一起更简单,更容易。 (有ThreadPool个对象,但没有记录。)

import glob, os, time
from multiprocessing import Pool

def filesize(path):
    time.sleep(0.1)
    return (path, os.path.getsize(path))

paths = glob.glob('*.py')
pool = Pool()                   # default: proc per CPU

with open("results.txt", 'w+') as dataf:
    for (apath, asize) in pool.imap_unordered(
            filesize, paths,
    ):
        print >>dataf, apath,asize

在results.txt输出

zwrap.py 122
usercustomize.py 38
tpending.py 2345
msimple4.py 385
parse2.py 499