2025-04-10

Python One-liner for Local QR Code Decoding

Because KeepassXC lacks the ability to decode QR code for TOTP setup and not all MFA implementations show the required secret in text format, I use the following snipet to read the QR code information locally:


  python -c 'from cv2 import QRCodeDetector; from PIL.ImageGrab import grabclipboard; import numpy as np; print(QRCodeDetector().detectAndDecode(np.array(grabclipboard()))[0])'

While there are many websites which can do the same, the TOTP secret is sensitive information that shouldn't be transmitted willy nilly to random websites.

You will need the following libraries installed: python-opencv>4, numpy, pillow. If you use uv then it is possible to have this as a nice script:

#!/usr/bin/env -S uv run --quiet --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "numpy",
#     "pillow",
#     "opencv-python>3",
# ]
# ///

from cv2 import QRCodeDetector
from PIL.ImageGrab import grabclipboard
import numpy as np

def main() -> None:
    im = grabclipboard()
    if im is None:
        print('Clipboard does not contain an image')
        return


    data, _, _ = QRCodeDetector().detectAndDecode(np.array(im))
    if data == '':
        # QR codes cannot encode the empty string (apparently)
        print('No QR code detected')
        return

    print(data)


if __name__ == "__main__":
    main()


Put this in your path somewhere and you can execute it like any other script and uv will handle installing depedencies etc.