【问题标题】:Barcode batch scanning - why does this code require a double scan to terminate?条码批量扫描 - 为什么此代码需要双重扫描才能终止?
【发布时间】:2021-07-27 02:54:54
【问题描述】:

我是一名 Python 程序员新手,正在尝试编写 Python 脚本来运行条码扫描站(Raspberry Pi 4、RPiOS、Python 3.7.3)。我想扫描一定数量的项目,完成后我想扫描不同的条形码来处理输入。如果达到批次计数,它将从那里发送一个 GPIO 信号,或者如果计数过高或过低,则直接终止程序。

我已经成功完成了我所写的内容,但有一个例外:当扫描第二个条形码以处理输入时,需要对其进行两次扫描以触发脚本的其余部分。我很困惑为什么会这样,而且我确信这是我忽略的简单事情。

import RPi.GPIO as GPIO
GPIO.setwarnings(False)
import time

good = 38

GPIO.setmode(GPIO.BOARD)

GPIO.setup(good,GPIO.OUT)
GPIO.output(good,GPIO.HIGH)

try:
    def batch_order():

        batch = input("Enter the number of parts on the order: ")
        barcode1 = input("Scan MASTER barcode: ")
        print("Begin scanning barcodes: ")
        count = 0
    
        while True:
            
            if input() == barcode1:
                count+= 1
                print("Part count: %s"%(str(count)))
            elif input() != barcode1:
                time.sleep(0.2)
                if batch == str(count):
                    print("Order complete! Now printing shipping label...")
                    time.sleep(0.2)
                    GPIO.output(good,False)
                    time.sleep(15)
                    GPIO.output(good,True)
                    break
                else:
                    print("Order incorrect, %s of %s parts scanned."%(str(count), batch))
                    time.sleep(2)
                    break
            
    batch_order()

except KeyboardInterrupt:
    
    GPIO.cleanup()
    print("QUIT")
    GPIO.cleanup()

我想要做的就是消除在elif input() != barcode1: 终止程序所需的双重扫描。任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: python python-3.x raspberry-pi4


    【解决方案1】:

    只需获取一次input() 并分配它

    value = input()
    
    if value == barcode1:
       ...
    else:  # there is also no other case
       ...
    

    【讨论】:

    • 通过消除else 子句中的input,您也消除了将字符串分配给变量的需要。
    • 确实!虽然我认为它是如此微不足道,他们会管理
    • 是的,这很简单。这很好地解决了这个问题。非常感谢大家!
    • @MPC_Quality 如果这解决了您的问题,请将其标记为答案并在其左侧打勾!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    相关资源
    最近更新 更多