gpt4 book ai didi

python - 多个线程在 Python 中同时写入日志文件

转载 作者:太空狗 更新时间:2023-10-29 20:33:02 27 4
gpt4 key购买 nike

我正在编写脚本以同时从多台计算机检索 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()

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

最佳答案

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

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): 周围放置锁,以允许每个线程在释放锁之前执行更大的工作 block 。

关于python - 多个线程在 Python 中同时写入日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26325943/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com