python多线程写文件问题_许多线程在Python中同时写入日志文件

python多线程写文件问题_许多线程在Python中同时写入日志文件,第1张

概述python多线程文件问题_许多线程在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.

解决方案

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.

总结

以上是内存溢出为你收集整理的python多线程写文件问题_许多线程在Python中同时写入日志文件全部内容,希望文章能够帮你解决python多线程写文件问题_许多线程在Python中同时写入日志文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/1012989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存