代码之家  ›  专栏  ›  技术社区  ›  Marcos Placona

多次写入文件

  •  0
  • Marcos Placona  · 技术社区  · 15 年前

    下面的python代码期望数据来自串行端口,并将其写入文件。

    import time
    import serial
    
    def write_log ( text ):
        f = open('logger.log', 'a')
        f.write( text )
        f.close()
    
    ser = serial.Serial()
    ser.port = "/dev/ttyS0"
    ser.baudrate = 4800
    ser.open()
    if ser.isOpen():
        while 1:
            while ser.inWaiting() <= 0:
                time.sleep(1)
                response = ser.read(ser.inWaiting())
                if len ( response ):
                    write_log( response )
                    print response
    

    它在某种程度上起作用,因为在一段时间之后,它开始挂起,使CPU一路上升,并且没有向.log文件中写入任何东西(或者有时只写入一段文本)。

    这里的过程相当密集,因为我的串行端口将每秒写入一个8字节的字符串,而这个python脚本应该随后接收它,并将其内容写入日志文件。

    我想问题是我打开和关闭文件太多了,这使得整个过程变得很慢。我不是python wizz,所以任何关于改进这段代码的帮助或建议都将非常感谢。

    提前谢谢你,

    2 回复  |  直到 15 年前
        1
  •  0
  •   user257111user257111    15 年前

    我认为这里的问题是您正在轮询更新。

    蟒蛇的 serial.read() 函数实际上会阻塞当前线程,直到线程上的某些内容变为可读,直到超时。因此,您应该做的是中断另一个线程来处理串行IO。让它无限循环,检查一个条件(主线程希望您保持监听,串行端口仍然可用)。此线程将执行以下操作:

    while ser.isOpen() && thisthread_should_keep_doing_this:
        response = ser.read(ser.inWaiting())
        if len(response):
            write_log(response)
            print response
    

    然后,当您希望它退出时,您的主线程集 thisthread_should_keep_doing_this=False 当你的从线程完成读取时,它会自杀。

    两件事:

    • 一定要有相对频繁的读取超时。
    • 不要“远程终止”线程。给它一个信息,让它自杀。远程杀死线程会造成可怕的混乱。

    见 http://pyserial.sourceforge.net/examples.html#miniterm

        2
  •  1
  •   Jonathan Leffler    15 年前

    你的代码中有一个无限循环,当出现问题时,或者串行设备不再打开时,你就不会中断它。

    可能使用:

    while ser.isOpen():
        while ser.inWaiting() <= 0:
            time.sleep(1)
            response = ser.read(ser.inWaiting())
            if len(response):
                write_log(response)
                print response
    

    甚至:

    while ser.isOpen() && ser.inWaiting() <= 0:
        time.sleep(1)
        response = ser.read(ser.inWaiting())
        if len(response):
            write_log(response)
            print response
    

    我对睡眠也不太确定,你最好还是在读的时候等数据出来。

    我在想,不知道serial类中可用的方法,我越觉得主循环应该尝试从串行设备中读取,如果当前没有可用的方法,则愉快地挂起,只有当输入方法指示没有更多输入时才终止-设备已在您身上关闭,或者在某种程度上失败了。