lpask - A tool to ask you which printer to use

So I've often wanted to send something out from vim (or indeed any other console tool). GVim on Windows shows you the system print dialog, but neovim certainly does not.

You could always pass in the appropriate printer name to the lp tool, but really, do you always remember the exact name of your printer? Especially if you have some auto discovery in CUPS and may at times be at one office and other times in another office (With different printers around).. Well it gets tiresome.

So I've hacked up a tool that you can use instead of the default lp. It simply shows a dialog (using PyQt5) and asks which printer to send it's standard input to. It's really quite simple and short, so I've not bothered to create a Github repository for it:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# vim: autoindent expandtab tabstop=4 sw=4 sts=4 filetype=python

import cups
import sys
import subprocess

from PyQt5.QtWidgets import QListWidget, QListWidgetItem
from PyQt5.QtWidgets import QApplication
from PyQt5           import QtCore


def get_printers():
    conn = cups.Connection()
    return conn.getDests()


class Dialog(QListWidget):

    def __init__(self):
        super().__init__()
        self.doubleClicked.connect(self.call_lp_command)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
        elif event.key() == QtCore.Qt.Key_Return:
            self.close_and_print(self.currentItem().text())
        else:
            super().keyPressEvent(event)

    def call_lp_command(self, index):
        self.close_and_print(index.data())

    def close_and_print(self, printer):
        subprocess.check_call(['lp', '-d', printer], stdin=sys.stdin)
        self.close()


if __name__ == '__main__':

    printers = get_printers()
    app    = QApplication(sys.argv)
    dialog = Dialog()

    for printerid, printer in sorted(printers.items()):
        item = QListWidgetItem(printerid[0])
        dialog.addItem(item)

    dialog.show()
    app.exec_()