Python on Raspberry Pi user input inside infinite loop misses inputs when hit with many

五迷三道 提交于 2019-12-05 09:34:57

You should probably read from stdin directly using code similar to the following:

import os
import sys
import select

stdin_fd = sys.stdin.fileno()
try:
    while True:
        sys.stdout.write("Scan barcode: ")
        sys.stdout.flush()
        r_list = [stdin_fd]
        w_list = list()
        x_list = list()
        r_list, w_list, x_list = select.select(r_list, w_list, x_list)
        if stdin_fd in r_list:
            result = os.read(stdin_fd, 1024)
            result = result.rstrip()
            result = [line.rstrip() for line in result.split('\n')]
            for line in result:
                print "Barcode scanned: %s" % line
except KeyboardInterrupt:
    print "Keyboard interrupt"

This code should handle the case that multiple lines are read at once. The read buffer size is arbitrary and you might have to change it depending on how much data you need to handle.

I know this is a little late, but after a closer look at the raw_input() docs I think it is pretty plain that raw_input is not designed to handle multi-line inputs. When it encounters a multi-line input it seems to only read the last line. (as demonstrated by your test). So my question is, how is raw_input getting a multi-line input in the first place? is the delay caused by the python program not being able to process the raw_input fast enough? Or is the delay inside the USB scanner/driver, and as a result it outputs two numbers instantaneously causing raw_input to process the last line without giving it an opportunity to process the first?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!