Im trying to periodcally write some measurements into a txt file. (some sorta logging).
To periodically run a function开发者_开发问答, there is a RepeatTimer class. And to run the function of updating the file I have a VTlog() function as below.
class RepeatTimer(Thread):
def __init__(self, interval, function, iterations=0, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.iterations = iterations
self.args = args
self.kwargs = kwargs
self.finished = Event()
def run(self):
count = 0
while not self.finished.isSet() and (self.iterations <= 0 or count < self.iterations):
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
count += 1
def cancel(self):
self.finished.set()
def LogVT():
tgt_picks = [t1,t2] #modify here for selective targets
for tgt in tgt_picks:
tt = tgt
file = ('c:/vtlogs_%s.txt' % str(tt.target_name))
x = str(tt.voltage('v_1p05_gfx_uncore')) + ', ' + str(tt.voltage('v_1p5_sm')) + ', ' + str(tt.temperature('pch_temp'))
q = time.strftime('%m/%d/%y, %H:%M:%S')
filehandle = open(file, 'a')
filehandle.write('\n' + q + ', ' + x)
filehandle.close()
time.sleep(3)
logtimer = RepeatTimer(60.0, LogVT)
logtimer.start()
the 'x' and 'q' works separetely when queried offline. t1 & t2 are some system attached with voltage & temp measurement device. api is already initiated.
My issue is, Im getting this at runtime:
Traceback (most recent call last):
File "C:\Python25\lib\logging\__init__.py", line 750, in emit
self.stream.write(fs % msg)
ValueError: I/O operation on closed file
Any explanation why??
I think you should check if open()
was done correctly and a file handle was in fact returned or an error occured before making any calls to write()
or close()
for that file handle.
------------CORRECTION-----------
You should check if open()
was done correctly but not for the reson I mentioned above. open()
will raise IOError
if it can't open the file, so this has nothing to do with your problem.
As Mat suggested, the threads are probably the cause of this. try something like:
...
def run(self):
count = 0
# creating a lock
lock = Lock()
while not self.finished.isSet() and (self.iterations <= 0 or count < self.iterations):
self.finished.wait(self.interval)
if not self.finished.isSet():
# call function with lock
self.function(lock, *self.args, **self.kwargs)
count += 1
...
def LogVT(lock):
tgt_picks = [t1,t2] #modify here for selective targets
for tgt in tgt_picks:
tt = tgt
file = ('c:/vtlogs_%s.txt' % str(tt.target_name))
x = str(tt.voltage('v_1p05_gfx_uncore')) + ', ' + str(tt.voltage('v_1p5_sm')) + ', ' + str(tt.temperature('pch_temp'))
q = time.strftime('%m/%d/%y, %H:%M:%S')
# lock while doing file operations
lock.acquire()
filehandle = open(file, 'a')
filehandle.write('\n' + q + ', ' + x)
filehandle.close()
# unlock
lock.release()
time.sleep(3)
...
精彩评论