PySerial脚本正在泄漏内存

2024-09-28 19:21:33 发布

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

我正在使用PySerial与集成电路板(ICB)配合使用,以持续监视几个红外线(IR)发射器/传感器单元的状态(即检查红外光束是否损坏或清除),并且我的程序似乎在大约一天之后就耗尽了计算机的内存。我怀疑这和PySerial有关,但不确定。在

一些项目背景:我有三个红外发射器/传感器单元,分别标记为1、2和3。如果没有一个光束断开,ICB通过串行连接输出字符串“0”。如果1号机组的光束断开,则输出字符串“1”,输出“2”代表2号机组,依此类推。可以肯定的是,在任何时间点,只有一根梁会断裂。我已经将ICB编程为每1/10秒输出一个字符串值(0、1、2或3)。在

通过下面的代码,我使用PySerial读取ICB输出,使用PyGame来记录每束光被打断的时间,达到最大时间量(全部在python2.7中):

import pygame, serial

def breakLoop(cumulative_break_time, max_cumulative_break_time, ser, is_beam_broken_org):
    elapsed_break_time = 0.
    clock.tick() #Start clock.
    while (cumulative_break_time + elapsed_break_time < max_cumulative_break_time):
        ser.flushInput()
        is_beam_broken = int(ser.read(1))
        if is_beam_broken == is_beam_broken_org:
            elapsed_break_time += clock.tick()/1000.
        else:
            break
    cumulative_break_time += elapsed_break_time
    return cumulative_break_time, elapsed_break_time

#Initialize objects and constants
ser = serial.Serial()
ser.baudrate = 115200
ser.port = 'COM3'
ser.open()
clock = pygame.time.Clock()
max_cumulative_break_time = 900. 
cumulative_break_time = 0.
out_file = open('test.csv','w')

while cumulative_break_time < max_cumulative_break_time: #Enter main event loop.
    ser.flushInput()
    is_beam_broken = int(ser.read(1))
    if is_beam_broken:
        print 'Beam %s broken.' % is_beam_broken
        cumulative_break_time, elapsed_break_time = breakLoop(cumulative_break_time, max_cumulative_break_time, ser, is_beam_broken)
        print 'Beam %s un-broken.' % is_beam_broken
        print 'Elapsed break time was: ', elapsed_break_time, ' s'
        print 'Cumulative break time is now: ', cumulative_break_time, ' s'
        print''
        out_file.write(','.join([str(is_beam_broken),str(elapsed_break_time)]) + '\n')
        out_file.flush()
out_file.close()
ser.close()
print '\n\nDone! Press any key to quit.'
raw_input('')

现在,代码功能正常,但是当我让它运行一天左右时,我得到一个“内存不足”的错误。我猜这和PySerial有关,因为我不断地从ICB读取输入……也许是因为我总是在刷新串行缓冲区?我不认为刷新内存内容会导致同样的内存不可用。。。在

另外,我阅读了PySerial的文档,发现了以下内容:

尚未实现/实现中可能存在的问题:客户端和服务器之间的RFC 2217流控制(对象内部缓冲区在从不读取时可能会占用所有内存)。

我不知道RFC2217是什么,但我知道我不知怎么的在泄露内存。在

我真的很感谢你的意见。我走对了吗?或者我的脚本内存使用过多是否有其他原因?在

当然,我很乐意进一步解释任何细节,如果他们有助于你帮助我:)


Tags: 内存timeisoutmaxserbeamprint