无限循环内的 Raspberry Pi 上的 Python 用户输入在被多次击中时会错过输入 [英] Python on Raspberry Pi user input inside infinite loop misses inputs when hit with many

查看:53
本文介绍了无限循环内的 Raspberry Pi 上的 Python 用户输入在被多次击中时会错过输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 Python 编写的非常基本的 parrot 脚本,它只是提示用户输入并将其打印回无限循环中.Raspberry Pi 有一个 USB 条码扫描器用于输入.

I have a very basic parrot script written in Python that simply prompts for a user input and prints it back inside an infinite loop. The Raspberry Pi has a USB barcode scanner attached for the input.

while True:
    barcode = raw_input("Scan barcode: ")
    print "Barcode scanned: " + barcode

当您以正常"速度扫描时,它工作可靠,命令输出如下所示:

When you scan at a "normal" speed it works reliably and the command output looks like this:

Scan barcode: 9780465031467
Barcode scanned: 9780465031467
Scan barcode: 9780007505142
Barcode scanned: 9780007505142

但是当你真的通过多次连续扫描来敲打它时,它可能会错过输入并且命令输出看起来像这样:

But when you really hammer it with many scans in close succession it is possible to make it miss inputs and the command output looks like this:

Scan barcode: 9780141049113
Barcode scanned: 9780141049113
Scan barcode: 9780465031467
Barcode scanned: 9780465031467
Scan barcode: 9780007505142
9780571273188
Barcode scanned: 9780571273188

注意 9780007505142 是如何输入但从未打印回来的.它在混乱中迷失.

Notice how 9780007505142 was input but never printed back. It got lost in the confusion.

查看我的测试视频演示:https://youtu.be/kdsfdKFhC1M

See a video demonstration of my test at: https://youtu.be/kdsfdKFhC1M

我的问题:这是使用 Pi 等低功耗设备的必然性吗?使用条码扫描器的用户是否总是能够超越硬件跟上的能力?

My question: Is this an inevitability of using a low powered device like a Pi? Will it always be true that a user with a barcode scanner will be able to out-run the hardware's ability to keep up?

推荐答案

您可能应该使用类似于以下的代码直接从 stdin 读取:

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"

这段代码应该处理一次读取多行的情况.read 缓冲区大小是任意的,您可能需要根据需要处理的数据量进行更改.

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.

这篇关于无限循环内的 Raspberry Pi 上的 Python 用户输入在被多次击中时会错过输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆