Python:在线程类中写入/附加到文件

2024-04-25 04:44:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着定期将一些测量值写入一个txt文件。(一些sorta日志)。在

要定期运行函数,有一个RepeatTimer类。为了运行更新文件的函数,我有一个VTlog()函数,如下所示。在

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

脱机查询时,“x”和“q”分别工作。t1和t2是一些带有电压和温度测量装置的系统。api已启动。在

我的问题是,我在运行时得到这个:

^{pr2}$

有什么解释吗??在


Tags: 函数selfdefcountargsfunctionkwargstgt
1条回答
网友
1楼 · 发布于 2024-04-25 04:44:44

我认为您应该检查open()是否正确完成,是否确实返回了一个文件句柄,或者在为该文件句柄调用write()或{}之前发生了错误。在

更正-

您应该检查open()是否正确执行,但不是针对我上面提到的原因。open()如果无法打开文件,它将引发IOError,因此这与您的问题无关。在

正如Mat所说,螺纹可能是造成这种情况的原因。尝试类似于:

...

    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)

...

相关问题 更多 >