Python Forum

Full Version: Combine two scripts and loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all

I am novice at python.

I have to scripts - one reads the barcode of a box and the other takes the weight of the box.

Barcode:

#!/usr/bin/ python
 
from evdev import InputDevice, ecodes, list_devices
from select import select
 
keys = {
    # Scancode: ASCIICode
    0: None, 1: u'ESC', 2: u'1', 3: u'2', 4: u'3', 5: u'4', 6: u'5', 7: u'6', 8: u'7', 9: u'8',
    10: u'9', 11: u'0', 12: u'-', 13: u'=', 14: u'BKSP', 15: u'TAB', 16: u'Q', 17: u'W', 18: u'E', 19: u'R',
    20: u'T', 21: u'Y', 22: u'U', 23: u'I', 24: u'O', 25: u'P', 26: u'[', 27: u']', 28: u'CRLF', 29: u'LCTRL',
    30: u'A', 31: u'S', 32: u'D', 33: u'F', 34: u'G', 35: u'H', 36: u'J', 37: u'K', 38: u'L', 39: u';',
    40: u'"', 41: u'`', 42: u'LSHFT', 43: u'\\', 44: u'Z', 45: u'X', 46: u'C', 47: u'V', 48: u'B', 49: u'N',
    50: u'M', 51: u',', 52: u'.', 53: u'/', 54: u'RSHFT', 56: u'LALT', 100: u'RALT'
}
dev = InputDevice("/dev/input/event3")
 
barcode = ""
while True:
    r,w,x = select([dev], [], [])
 
    for event in dev.read():
        if event.type == 1 and event.value == 1:
             barcode += (keys[event.code])
    if (len (barcode)) > 13:
     break;
 
with open('outputbarcode.txt', 'a+') as myfile:
     myfile.write(barcode)
 
 
print (barcode)
Scale:

#!/usr/bin/ python
 
 
import time
import serial
 
 
ser = serial.Serial(
 port='/dev/ttyUSB0',
 baudrate = 9600,
 parity=serial.PARITY_NONE,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.EIGHTBITS,
 timeout=None
)
 
 
while 1:
 x=ser.readline().decode('utf-8')
 with open('outputbarcode.txt', 'a+') as myfile:
     myfile.write(x)
 
 
 print(x)
The both output to my txt file.

I am trying to combine them together so they can accept the barcode from the scanner and the weight from the scale.

When I run them individually, they close after each run.

I need this to stay open and constantly looking for these inputs but I am not sure how to do this.

This will run on a raspberry pi and will ideally be headless.

Am I on the right path?

Any help would be greatly appreciated.

BMC
To do this, you'll need to refactor these scripts into functions and/or classes and import them into another script to run the code. By refactoring this way, you can run the code in a loop without it closing.
thank you. I will see what I can do.