Skip to content

Instantly share code, notes, and snippets.

@CLCL
Last active July 15, 2019 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CLCL/37194ad59a021d8fbc57abd9bade76b3 to your computer and use it in GitHub Desktop.
Save CLCL/37194ad59a021d8fbc57abd9bade76b3 to your computer and use it in GitHub Desktop.
バーコードスキャナのHIDデバイスをつないで、コンソールでスクリプトを実行したら入力待ち、スキャンしたら画面に表示する。
#!/usr/bin/python3
#https://codeday.me/jp/qa/20190304/361513.html
import signal, sys
import evdev
from evdev import InputDevice, ecodes, list_devices, categorize
# キースキャンコードとキャラクターの対応リスト
scancodes = {
# Scancode: ASCIICode
2: '1', 3: '2', 4: '3', 5: '4',
6: '5', 7: '6', 8: '7', 9: '8',
10: '9', 11: '0', 28: 'CRLF'
}
barCodeDeviceString = 'USB BARCODE SCANNER USB BARCODE SCANNER'
devices = map(InputDevice, list_devices())
for device in devices:
print(device.name)
if device.name == barCodeDeviceString:
dev = InputDevice(device.path)
if not 'dev' in locals():
sys.exit("Device '{barCodeDeviceString}' not connected.".format(**locals()))
def signal_handler(signal, frame):
print("\nStopping")
dev.ungrab()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
dev.grab()
def main():
code = ''
for event in dev.read_loop():
if event.type == evdev.ecodes.EV_KEY:
data = evdev.categorize(event)
if data.keystate == 1: # Down events only
key_lookup = scancodes.get(data.scancode) or ''
if key_lookup == 'CRLF':
print(code)
code = ''
else:
code += key_lookup
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment