加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Raspberry Pi上的Python用户输入无限循环内部输入时很多输入错

发布时间:2020-12-16 22:45:35 所属栏目:Python 来源:网络整理
导读:我有一个用Python编写的非常基本的parrot脚本,只是提示用户输入并将其打印回无限循环内. Raspberry Pi附带USB条形码扫描仪,用于输入. while True: barcode = raw_input("Scan barcode: ") print "Barcode scanned: " + barcode 当您以“正常”速度扫描时,它

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

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

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

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

但是当你真的用很多扫描连续敲击它时,有可能让它错过输入,命令输出如下所示:

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

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

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

我的问题:这是不可避免的使用像Pi这样的低功耗设备?拥有条形码扫描仪的用户是否能够超越硬件的跟进能力?

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

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,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"

此代码应处理一次读取多行的情况.读取缓冲区大小是任意的,您可能需要根据需要处理的数据来更改它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读