简介
使用python在windows和linux的实现获取扫码枪扫描的信息,扫码枪输出的是按键信息,监听按键信息
window实现
from pynput import mouse,keyboard
CODE = ""
# 处理键盘输入的数据
def on_release(key):
global CODE
try:
CODE += key.char
print("key:",key)
except Exception as e:
try:
if key == key.enter: #如果扫码枪中的数据是回车enter按键
print("CODE:",CODE)
CODE = ""
except Exception as e:
CODE = ""
def main():
#监听键盘扫码枪输入
with keyboard.Listener(on_release=on_release) as listener:
listener.join()
linux实现
1.扫描/proc/bus/input/devices看你的设备是否在系统中
2.解析cat /proc/bus/input/devices输出的信息,查看event的id
3.根据event id去组装/dev/input/event你的id
4.用open和read去读取event里面的输入
from evdev import InputDevice, ecodes, list_devices, categorize
import signal, sys
SCAN_CODE_FILE = "/home/wai/hik/code/scan_code.txt"
dev = None
def signal_handler(signal, frame):
global dev
print('Stopping')
dev.ungrab()
sys.exit(0)
def main():
global dev
scancodes = {
# 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'
}
barCodeDeviceString = "Honeywell 1900-C"
devices = map(InputDevice, list_devices())
for device in devices:
print("devices name",device.name)
if device.name == barCodeDeviceString:
dev = InputDevice(device.fn)
signal.signal(signal.SIGINT, signal_handler)
print("dev",dev)
if dev!=None:
dev.grab()
barcode = ""
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
data = categorize(event)
if data.keystate == 1 and data.scancode != 42: # Catch only keydown, and not Enter
if data.scancode == 28:
print(barcode)
fileWrite = open(SCAN_CODE_FILE,"w",encoding='utf-8');
fileWrite.write(barcode)
fileWrite.close()
barcode = ""
else:
barcode += scancodes[data.scancode]