2016-10-20 22 views
4

我有一個非常基本的鸚鵡腳本用Python編寫,只需提示用戶輸入並在無限循環內打印回來。 Raspberry Pi有一個USB條形碼掃描器,用於輸入。Python上Raspberry Pi用戶輸入內部無限循環錯過輸入時,許多命中

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

我的問題:這是使用像丕低功率設備的必然性?用條碼掃描器的用戶是否能夠保證硬件能夠跟上運行的能力?

+0

Java你試過另一種語言嗎?看看我在那裏做了什麼? – Jay

+0

@Jay No.你認爲如果我用Java運行測試是不可能超出它的嗎? –

+0

我會說爲了測試目的而嘗試它。也許它是一個緩慢的圖書館,也許是一個緩慢的語言,也許是CPU不能保持聯繫。我會說,如果你使用c/C++/java,你肯定會有更好的性能。 c/C++的問題在於它很難設置,而且您可能找不到要查找的庫。 Java更簡單,設置更簡單,性能得到保證。 – Jay

回答

1

我知道這有點晚了,但仔細看看raw_input()docs後,我認爲raw_input不是用來處理多行輸入的。當它遇到多行輸入時,它似乎只讀最後一行。 (如你的測試所證明的)。所以我的問題是,raw_input如何首先獲取多行輸入?是由python程序不能夠足夠快地處理raw_input引起的延遲?或者是USB掃描器/驅動器內的延遲,因此它會立即輸出兩個數字,導致raw_input處理最後一行,而不給它處理第一行的機會?

2

您應該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, 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緩衝區大小是任意的,您可能必須根據需要處理的數據量來更改它。