Skip to content

Instantly share code, notes, and snippets.

@CLCL
Last active July 15, 2019 21:52

Revisions

  1. CLCL revised this gist Jul 15, 2019. 1 changed file with 7 additions and 4 deletions.
    11 changes: 7 additions & 4 deletions barcode.py
    Original file line number Diff line number Diff line change
    @@ -9,8 +9,8 @@
    # キースキャンコードとキャラクターの対応リスト
    scancodes = {
    # Scancode: ASCIICode
    2: '1', 3: '2', 4: '3', 5: '4',
    6: '5', 7: '6', 8: '7', 9: '8',
    2: '1', 3: '2', 4: '3', 5: '4',
    6: '5', 7: '6', 8: '7', 9: '8',
    10: '9', 11: '0', 28: 'CRLF'
    }

    @@ -23,8 +23,11 @@
    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('Stopping')
    print("\nStopping")
    dev.ungrab()
    sys.exit(0)

    @@ -46,4 +49,4 @@ def main():
    code += key_lookup

    if __name__ == '__main__':
    main()
    main()
  2. CLCL revised this gist Jul 15, 2019. No changes.
  3. CLCL created this gist Jul 15, 2019.
    49 changes: 49 additions & 0 deletions barcode.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #!/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)

    def signal_handler(signal, frame):
    print('Stopping')
    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()